3

Saw this code for regular expression validation of an email address via data annotations.

I Can't work out the purpose of 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")]
1

4 Answers 4

5

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.

4

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..

1
  • 1
    I tried this solution and it works fine for server-side validation. However, EmailValidationAttribute won't wire up for client-side validation. Just using RegularExpressionAttribte with the regular expression you provider works great on the client-side as well as server-side though. Something like this: [RegularExpression(@"^([\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})?)$", ErrorMessage = "Email address must be a valid email address.")] Oct 16, 2012 at 16:15
2

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 @.

0

Double-backslash are mandatory because backslash is an Escape character in C#. An alternative could be @".+\@.+\..+"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.