2

Ok so this is a really simple scenario which I can't figure out since I've just started with MVC. I have created a custom password validator to use both client and server side. For the meantime the client-side validator does nothing but check the length (it will do more than this once I get it working). The server-side validation works fine. This is the client side implementation

$.validator.unobtrusive.adapters.add("password",
    function (options) {
        options.rules['password'] = {};
        options.messages['password'] = options.message;
    }
);
$.validator.addMethod("password", function (value, element, params) {
    if (value.length < 8 || value.length > 15) {
        return false;
    }
    return true;
}); 

I only want this validator to fire when the form is submitted.

Currently, as soon as you start typing it tells you that your password is invalid until the password meets the length requirements. I want it to act like the standard 'Required' validators I have on other form fields where they only validate the input once the form is submitted.

James Hay
  • 7,115
  • 6
  • 33
  • 57

1 Answers1

1

Right so I found a similar question with some answers on disabling the keyup feature here: ASP.net MVC 3 jQuery Validation; Disable Unobtrusive OnKeyUp? But I found another way to do it, which doesn't involve writing extra lines of javascript or turning the functionality off on all fields. Basically, I just changed the actual function inside the jquery.validation.js file to check for an attribute called nokeyup and if it's found then return. You can find the onkeyup function not too far from the start of the file. It originally looks like this

onkeyup: function(a, b) {
    if ( b.which === 9 && this.elementValue(a) === '' ) {
        return;
    }
    else if ( a.name in this.submitted || a=== this.lastActive ) {
        this.element(a);
    }
},

So I changed it to

onkeyup: function (a, b) {
    if (b.which === 9 && this.elementValue(a) === "") { 
        return;
    }
    else if (a.getAttribute('nokeyup')) { // Added this statement
        return;
    } 
    else if ( a.name in this.submitted || a=== this.lastActive ) {
        this.element(a);
    }
},

After that all that I had to do was add the 'nokeyup' attribute to my text boxes which I didn't want to fire the validation for until form submission and voila.

Community
  • 1
  • 1
James Hay
  • 7,115
  • 6
  • 33
  • 57