Saw this code for regular expression validation of an email address via data annotations.
I Can't work out the purpose of开发者_如何学JAVA the double backslash.
To me it's saying there must be a backslash in the email - but I know that this isn't what it is doing!!!
[RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email")]
The backslash is an escape character both in C# and in a regex. So, in C#, "\\"
equals to a single backslash. The resulting backslash is then used to escape the .
, which is a metacharacter and therefore must be escaped. I don't know why the @
is escaped however.
For MVC2 Pattern
using System.ComponentModel.DataAnnotations;
public class EmailValidationAttribute: RegularExpressionAttribute
{
public EmailValidationAttribute() : base(@"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$")
{
}
}
And then use
[EmailValidation(ErrorMessage="Not a valid Email Address")]
public string Email { get; set; }
This will work perfectly..
Certain characters have special meaning when escaped in a regular expression. For instance \d means a number.
In C# the backslash has a similar function. For instance \n means newline. In order to get a literal backslash in C# you must escape it...with a backslash. Two together is the same as a literal backslash.
C# has a way of denoting a string as literal so backslash characters are not used - prepend the string with @.
Double-backslash are mandatory because backslash is an Escape character in C#. An alternative could be @".+\@.+\..+"
精彩评论