Search code examples
jqueryasp.net-mvcvalidationunobtrusive-validationemail-validation

Immediately validate email fields on client side


I have the following property in my view model:

[EmailAddress]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

And render this with the following razor view:

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

This produces the following html output (see type="email", which is what I want):

<input data-val="true" data-val-email="The Email field is not a valid e-mail address." id="Email" name="Email" type="email" value="">

I also have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true. The validation for required etc. works as expected. But the validation for this email field is not triggered immediately after changing a character in the input field or after focus another input field.

First of all, my browser gives the message that it's not a valid email address. But when I enter sfsdf@sdfsfd, my browser (Chrome) detects it as a valid email address and then the email validator from ASP.NET MVC says that it's not a valid format. But the ASP.NET validator is triggered only when i hit the submit button (also the browser validation is only triggered on submit, but this is not a problem because I will disable the browser validation anyway).

When I use @Html.TextBoxFor() instead of @Html.EditorFor() it produces the following markup (with type="text"):

<input data-val="true" data-val-email="The Email field is not a valid e-mail address." id="Email" name="Email" type="text" value="">

And now, the validation is triggered immediately when changing any character in the inputfield or focus another one. By I need to have the type="email".

Is it possible to force the validation immediately also on email fields?


Solution

  • Type=email is HTML5 markup. I'm comparing 2 of my projects where the other one uses old jquery validator plugin and it does not seem to work with email type. However the newer project uses the latest validator and it does work fine.

    Try updating your jquery validator plugin.