Validation of email addresses (ASP.NET)
I have a asp.net web form where i can can enter an email address.
i need to validate that field with email addresses ONLYin the below pettern :
xxx@home.co.uk xxx@home.com xxx@homegroup.com
Please help
A regular expression to validate this would be:
^[A-Z0-9._%+-]+((@home.co.uk)|(@home.com)|(@homegroup.com))$
C# sample:
string emailAddress = "jim@home.com";
string pattern = @"^[A-Z0-9._%+-]+((@home.co.uk)|(@home.com)|(@homegroup.com))$";
if (Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase))
{
// email address is valid
}
VB sample:
Dim emailAddress As String = "jim@home.com"
Dim pattern As String = "^[A-Z0-9._%+-]+((@home.co.uk)|(@home.com)|(@homegroup.com))$";
If Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase) Then
' email address is valid
End If
Here's how I would do the validation using System.Net.Mail.MailAddress
:
bool valid = true;
try
{
MailAddress address = new MailAddress(email);
}
catch(FormatException)
{
valid = false;
}
if(!(email.EndsWith("@home.co.uk") ||
email.EndsWith("@home.com") ||
email.EndsWith("@homegroup.com")))
{
valid = false;
}
return valid;
MailAddress
first validates that it is a valid email address. Then the rest validates that it ends with the destinations you require. To me, this is simpler for everyone to understand than some clumsy-looking regex. It may not be as performant as a regex would be, but it doesn't sound like you're validating a bunch of them in a loop ... just one at a time on a web page
Depending on what version of ASP.NET your are using you can use one of the Form Validation controls in your toolbox under 'Validation.' This is probably preferable to setting up your own logic after a postback. There are several types that you can drag to your form and associate with controls, and you can customize the error messages and positioning as well.
There are several types that can make it a required field or make sure its within a certain range, but you probably want the Regular Expression validator. You can use one of the expressions already shown or I think Visual Studio might supply a sample email address one.
链接地址: http://www.djcxy.com/p/92820.html上一篇: 电子邮件正则表达式问题
下一篇: 验证电子邮件地址(ASP.NET)