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.

3

4 Answers 4

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")]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.