How to validate e-mail and URL in ASP .NET.

The control and the RE’s

Probability the easiest to validate the user input and check if the user entered with a valid e-mail or URL address is using the RegularExpressionValidator. It is control included in ASP .NET 3.5 which you can use to prevent users from submitting the wrong type of data into a database table.

The RegularExpressionValidator enables you to compare a value against a regular expression. You can use a regular expression to represent string patterns such as email addresses, Social Security numbers, phone numbers, dates and product codes.

We have several options to represent e-mails as a regular expression. Above I show some of them:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

This regular expression matches an email address that contains non-whitespace characters, followed by an @ sign, followed by non-whitespace characters, followed by a period, followed by more non-whitespace characters.

^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

This one will accept multiple e-mails separated only by semi-colons.

\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*

This one validates 1 or more email addresses. The e-mail addresses can be delimited with either comma or semicolon. White space is allowed after delimiter, but not necessary.

^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$

Matches a valid email address including ip’s and or port number after the @. This ER matches address like this:  [email protected], [email protected]:8080 or [email protected]

Below some samples for Regular Expression using to validate domains, URL’s and IP’s.:

^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$

This regular expression tests the validity of a domain or hostname.

(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

This one matches any internet URLs.

^(([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+))$

And finally, this one will match simple IP addresses.

Ebook Download
View all
Learn
View all