AJM
AJM

Reputation: 32490

C# Regular Expression for email validation in DataAnnotations - Double backslash

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")]

Upvotes: 3

Views: 11889

Answers (4)

sushil
sushil

Reputation: 41

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

Upvotes: 4

Etienne de Martel
Etienne de Martel

Reputation: 36984

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.

Upvotes: 5

Erik Noren
Erik Noren

Reputation: 4339

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

Upvotes: 2

Sam B
Sam B

Reputation: 2481

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

Upvotes: 0

Related Questions