Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email address validation in C# MVC 4 application: with or without using Regex [duplicate]

I have an MVC 4 web application and I need to enter and validate some email addresses, without sending an email to the user's email address.

Currently I am using basic regex email validation with this pattern:

[RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
        ErrorMessage = "Please enter correct email address")]

Although this is validating email addresses, it passes [email protected] as a valid email address. For the moment I have a validation that requires symbols @ symbols . symbols where the symbols can be numeric/alphabetic and ._- .

I need more standard email validation for my MVC 4 application. How do I do that?

like image 654
dlght Avatar asked Sep 11 '25 01:09

dlght


2 Answers

You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example

[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
like image 192
Ehsan Avatar answered Sep 12 '25 14:09

Ehsan


Expanding on Ehsan's Answer....

If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute Class in code.

private static bool IsValidEmailAddress(string emailAddress)
{
    return new System.ComponentModel.DataAnnotations
                        .EmailAddressAttribute()
                        .IsValid(emailAddress);
}

If you are considering REGEX to verify email address then read:

I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack

like image 32
Habib Avatar answered Sep 12 '25 14:09

Habib