[c#] Email address validation using ASP.NET MVC data type attributes

I have some problems with the validation of a Email.

In my Model:

[Required(ErrorMessage = "Field can't be empty")]
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
public string ReceiverMail { get; set; }

In my view:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Html.TextBoxFor(m => m.ReceiverMail, new { @placeholder="E-mail"}) <br />
@Html.ValidationMessageFor(m => m.ReceiverMail)

Now it is correctly showing me "Field can't be empty" when you leave the field empty. But when you fill in an invalid email address like: "fwenrjfw" then the form does not say "E-mail is not valid".

How can I get the form to validate the input as an email address? I am looking for some help with this.

This question is related to c# asp.net-mvc validation email-validation

The answer is


[Required(ErrorMessage = "Please enter Social Email id")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }

As per the above this will fix server side validation of an Email Address:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

However...

If you are using JQuery client side validation you should know that the Email validates differently server side (model validation) to client side (JQuery validation). In that test@example (a top level domain email address) would fail server side but would validate fine on the client side.

To fix this disparity you can override the default client side email validation as follows:

$.validator.methods.email = function (value, element) {
    return this.optional(element) || /^[a-z0-9._]+@[a-z]+\.[a-z.]+/.test(value);
}

Used the above code in MVC5 project and it works completely fine with the validation error. Just try this code:

   [Required]
   [Display(Name = "Email")]
   [EmailAddress]

   [RegularExpression(@"^([A-Za-z0-9][^'!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ][a-zA-z0- 
    9-._][^!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ]*\@[a-zA-Z0-9][^!&@\\#*$%^?<> 
        ()+=':;~`.\[\]{}|/,?€ ]*\.[a-zA-Z]{2,6})$", ErrorMessage = "Please enter a 
   valid Email")]


   public string ReceiverMail { get; set; }

Scripts are usually loaded in the end of the html page, and MVC recommends the using of bundles, just saying. So my best bet is that your jquery.validate files got altered in some way or are not updated to the latest version, since they do validate e-mail inputs.

So you could either update/refresh your nuget package or write your own function, really.

Here's an example which you would add in an extra file after jquery.validate.unobtrusive:

$.validator.addMethod(
    "email",
    function (value, element) {
        return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
    },
    "This e-mail is not valid"
);

This is just a copy and paste of the current jquery.validate Regex, but this way you could set your custom error message/add extra methods to fields you might want to validate in the near future.


If you are using .NET Framework 4.5, the solution is to use EmailAddressAttribute which resides inside System.ComponentModel.DataAnnotations.

Your code should look similar to this:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

Try Html.EditorFor helper method instead of Html.TextBoxFor.


I use MVC 3. An example of email address property in one of my classes is:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[Email(ErrorMessage = "The email address is not valid")]
public string Email { get; set; }

Remove the Required if the input is optional. No need for regular expressions although I have one which covers all of the options within an email address up to RFC 2822 level (it's very long).


if you aren't yet using .net 4.5:

/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
    static EmailAnnotation()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
    }

    /// <summary>
    /// from: http://stackoverflow.com/a/6893571/984463
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
    {
        return "E-mail is not valid";
    }
}

Then you can do this:

    public class ContactEmailAddressDto
    {
        public int ContactId { get; set; }
        [Required]
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }
    }

You need to use RegularExpression Attribute, something like this:

[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]

And don't delete [Required] because [RegularExpression] doesn't affect empty fields.


[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to email-validation

Email address validation in C# MVC 4 application: with or without using Regex Email address validation using ASP.NET MVC data type attributes Best Regular Expression for Email Validation in C# Email Address Validation in Android on EditText How to validate an email address in PHP Can there be an apostrophe in an email address? How to check for valid email address? How to check edittext's text is email address or not? How to validate an Email in PHP? HTML5 Email input pattern attribute