0

I am trying to validate that an email address entered by the user is a valid email address. I have tried to use the following data annotation which I read should work:

    [Required]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    public string Email { get; set; }

So as you can see I have used the [DataType(DataType.EmailAddress)]. This does not seem to work. Is there any other method that I can use to check that an email address is valid. I have spent the last 108 hours working on this and I feel that it is about time I move on.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
user3412625
  • 99
  • 1
  • 8

4 Answers4

1

You can use regexp validation

[RegularExpression("/^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$/", ErrorMessage = "Lorem ipsum bla bla")]
Sylwekqaz
  • 329
  • 2
  • 9
1

If you use the following mark-up it will render an html 5 input type email:

Markup

 @Html.EditorFor(m => m.Email)
 @Html.ValidationMessageFor(m => m.Email)

Rendered output

<input class="text-box single-line" data-val="true" 
 data-val-required="The Email Address field is required." 
 id="Email" name="Email" type="email" value="">

This will prevent invalid submission for html 5 compliant browsers.

jsFiddle

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
0

The System.Net.Mail.MailAddress class can handle this. It will throw a FormatException if the address is in an unrecognized format. See this on MSDN: http://msdn.microsoft.com/en-us/library/591bk9e8(v=vs.110).aspx

Tim
  • 126
  • 1
  • 5
0

As per this answer:

Datatype.Emailaddress derives from DataTypeAttribute and adds client-side e-mail validation you also need to set <% Html.EnableClientValidation(); %> in your corresponding view.

As hutchonoid points out, this will generate an HTML5 <input type="email" ... /> input field, which will allow the browser to pre-validate for you as well as provide the "Email" keyboard on mobile devices.

For server-side valdiation you could use the DataAnnotations library by using EmailAddressAttribute:

using System.ComponentModel.DataAnnotations; 

[Required]
[EmailAddress]
[DataType(DataType.EmailAddress)]
[DisplayName("Email Address")]
public String Email { get; set; }

Alternatively, you could use the RegularExpressionAttribute and get both client and server side validation, but without the HTML5 field rendering.

Community
  • 1
  • 1
Zhaph - Ben Duguid
  • 26,785
  • 5
  • 80
  • 117