181

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Java Afca
  • 2,217
  • 4
  • 16
  • 10

12 Answers12

364

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; }
Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Shittu Joseph Olugbenga
  • 6,396
  • 5
  • 26
  • 37
  • Thank you @Shittu Olugbenga! But I can't understand why this doesn't work: `[DataType(DataType.EmailAddress, ErrorMessage = "Error message.")]` – Wellington Zanelli Sep 18 '14 at 12:34
  • 19
    @Wellington Zanelli - The DataType(DataType.EmailAddress) cannot be used to validate user input. It is only used to provide a UI hint for rendering the values using the display / editor templates. – Liam May 07 '15 at 16:41
  • 4
    @Jni `DataType.EmailAddress` is not about validation. It's about data presentation... – Sebastian Xawery Wiśniowiecki May 19 '15 at 21:16
  • 3
    I have the same issue and for me email validation works fine except for emails like 'name@xxx'. Has anyone else seen this? – Kremena Lalova Nov 03 '15 at 19:13
  • 5
    @KremenaLalova `name@xxx` is a completely valid email address, so there is nothing wrong with that method. Consider the example `username@localhost` for example. – John Bergman Dec 11 '15 at 17:11
  • Actually on further investigation it's the Required annotation that's failing, not the EmailAddress annotation. – Nathan McKaskle Jan 13 '17 at 18:18
  • @markzzz why do you think "this answer is really wrong and must be ignored"?. The 'EmailAddress' attribute is provided by MS and has been around for years. – Shittu Joseph Olugbenga Mar 12 '18 at 13:51
  • Didn't work for me - until I included the jQuery reference in the View. – Gary Oct 04 '18 at 14:36
  • Is there any way to enforce the presence of .com, .org, or .something? – variable Jan 07 '22 at 04:51
  • **name@xxx** is **not a valid email address**. Try to buy any adobe product with this email address and you would know – Sujoy Mar 02 '22 at 10:22
40

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

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
hazimdikenli
  • 5,709
  • 8
  • 37
  • 67
35

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Alexander Imra
  • 832
  • 5
  • 11
  • 10
    Old skool is nice but since Microsoft implemented an attribute it addresses bugs and oversights that can happenin in certain situations, countries, time zones or planets. SO its best to use a fully released code base than custom regex. Does your regex take into consideration the new top level domains, for example? – Piotr Kula Dec 10 '13 at 15:29
  • 2
    That regex looks like it will fail for any email address with foreign characters or many non-standard characters in it. – EricP May 28 '14 at 19:26
  • 3
    Validating email addresses with regex is usually a terrible idea... but if you must, there's an excellent reference here.. http://www.regular-expressions.info/email.html – Molomby Jul 23 '14 at 04:18
  • 9
    This regex and website is wrong. There are plenty of new TLD more than 6 characters. Don't follow this one. – jsgoupil Jul 02 '15 at 01:09
  • 1
    Regular expression is still better. Microsoft's EmailAddress data annotation accepts name@xxx as a valid email address. Try buying any Adobe product by using this email address and it will be flagged as an invalid format. – Sujoy Mar 02 '22 at 10:26
  • Please do not use `Regex` to validate Email Address: https://michaellong.medium.com/please-do-not-use-regex-to-validate-email-addresses-e90f14898c18 – Rahul Sharma May 11 '23 at 06:03
15

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; }
    }
mcfea
  • 1,129
  • 15
  • 22
10

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

Peter Smith
  • 5,528
  • 8
  • 51
  • 77
  • 3
    What namespace is your Email attribute in? Or is it a custom attribute? – User Nov 26 '13 at 17:17
  • 6
    MVC 4 uses `[EmailAddress]` and you need to have `using System.ComponentModel.DataAnnotations; ` – Piotr Kula Dec 10 '13 at 15:27
  • 1
    It would seem that no matter what I do, the use of either `Email` or `RegularExpression` makes the field required. Removing the `Required` annotation has no effect. Any suggestions on what to do to make fields with `RegularExpression` validation accept empty fields? – Eric K Mar 06 '15 at 20:16
  • @QuantumDynamix Try adding an empty string test to your regular expression as an option. Never tried it, but who knows? – Peter Smith Mar 07 '15 at 09:04
8
[Required(ErrorMessage = "Please enter Social Email id")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }
4

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; }
  • 2
    Welcome to StackOverflow. Code-only answers are not considered to be a good practice. Please elaborate what this does and how it resolves the problem. – quinz Jun 06 '19 at 11:22
1
[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]
Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
  • 6
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Adriaan Sep 22 '20 at 12:58
  • This regexp seems to block **valid** emails containing `.`, printable characters `!#$%&'*+-/=?^_\`{|}~` as stated in [RFC 5322](https://tools.ietf.org/html/rfc5322) in the `local-part`; also `domain-part` may be an IP address – Nowhere Man Sep 22 '20 at 13:44
  • Please do not use `Regex` to validate Email Address: https://michaellong.medium.com/please-do-not-use-regex-to-validate-email-addresses-e90f14898c18 – Rahul Sharma May 11 '23 at 06:05
1

I have had this issue as well, you can try this it's works for me

[RegularExpression("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Email is not valid")]
  • Please do not use `Regex` to validate Email Address: https://michaellong.medium.com/please-do-not-use-regex-to-validate-email-addresses-e90f14898c18 – Rahul Sharma May 11 '23 at 06:03
0

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.

Tiramonium
  • 557
  • 5
  • 15
0

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);
}
Jon Ryan
  • 1,497
  • 1
  • 13
  • 29
0

I have had this issue as well, and when you use [EmailAddress] annotation it allows them to put in a email like this test@email and does not require an actual .com. I found the best way to do this is like this. I didn't actually write this RegEx I found it on another question in Stackoverflow, or maybe one I asked lol. However the regular expression says before the @ you can add letters and numbers with a hyphon (-) and but no special characters. The @ sign you have to add something like gmail, aol, live, yahoo, etc... It haves to have at least one character after the @ sign. Then at the period or dot . you must put something no less than two character like .com, .net, .org, .infor I don't know many emails ending with .au which means Australia just in case. Now if you want to break it down you would have to go to this site RegEx for better explanation at the bottom.

[Required, MinLength(1), DataType(DataType.EmailAddress), EmailAddress, MaxLength(50), Display(Name = "Email")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string EMail { get; set; }
AlThePal78
  • 793
  • 2
  • 14
  • 25