Paul Hiles
Paul Hiles

Reputation: 9788

input type = email jquery validate overriding mvc data annotation

I have the following property on my viewmodel:

    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(RegularExpressions.Email, ErrorMessage = "Email is not valid")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

In MVC4, because of the DataType annotation, this is rendered as <input type="email"... which is great for devices that change the keyboard to include @ such as the ipad. Unfortunately, jquery.validate seems to automatically validate the field using its own regex so if a user enters an incorrect email, the jquery validate error message is shown and not the one I defined in the attribute.

What is the best way to stop jquery.validate doing this automatic validation so that my regex is used instead?

Upvotes: 1

Views: 2141

Answers (2)

Paul Hiles
Paul Hiles

Reputation: 9788

Found this answer by Dave Ward suggesting a workaround which does not involve changing external js libraries.

Just add the following after your jquery and jquery.validate includes:

$.validator.methods.email = function (value, element) {
    return this.optional(element) || true; };

Upvotes: 1

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

In short the answer for this is that MVC does not support automatically overriding JQuery validation message, or suppressing the validation.

However you can relatively easily localize the JQuery validation. Here are a few examples of how to do that:

How to change JQuery validation text directly

JQuery validation localization plug in

** Warning - I have not tested these myself, but in general you want to include your scripts right after the JQuery reference on your page

Upvotes: 1

Related Questions