4
votes

I have an ASP.NET MVC login form, that uses client-side unobtrusive validation.

My login model has a UserName with a [Required] attribute. Most of the usernames entered will be email-addresses, so on touch-devices, I'd like to show a nice email-friendly keyboard. So I set type="email"on the <input>, like so:

@Html.TextBoxFor(m => m.UserName, new { type = "email" })

Now, I don't want to have the email-address validated (since non-email usernames are valid), but somehow, since I have a [Required] attribute, the default jquery.validate email validation kicks in as well, giving me a ´Please enter a valid email address´ error.

Is there any way to prevent this, while keeping the required-field validation?

2

2 Answers

4
votes

The solution turned out to be quite simple:

$('#loginform').data("validator").settings.rules["UserName"].email = false;

An input field is validated using multiple rule sets (from jquery.validate.js):

    var data = $.validator.normalizeRules(
    $.extend(
        {},
        $.validator.metadataRules(element),
        $.validator.classRules(element),
        $.validator.attributeRules(element),
        $.validator.staticRules(element)
    ), element);

The attributeRules are what cause the email validation to be activated, but since staticRules take precendce, the email-validation is de-activated with our assignment above.

0
votes

Maybe a dum suggestion but how about removing the [Required] attribute and handling it in the controller on post action? :)