Search code examples
jquery-validation-engine

jQuery-Validation-Engine -- Making sure fields values do not equal


I'm using jQuery-Validation-Engine to do some client side checking before sending a form to the server.

I know you can check to make sure two fields match using validate[equals[fieldId]] where fieldId is the id of the field you want to match. Useful if you want to make sure passwords match, for example.

Now I am trying to find a way to make sure fields don't match. For example, if I wanted to make sure a password field did not match a username field.

Has anyone been able to get this to work? Any other ideas?

Thanks.


Solution

  • After some research and trial and error, I answered my own question. I'll post what I did here so others who need to do the same thing will have a reference.

    Turns out you need to create a new custom function in much the same way you add a custom regex. How to apply a custom regex is fairly well documented, but there's not much on how to implement a custom function (without calling a 3rd party function).

    Digging around in the language file gives a better idea of how to handle it.

    I had to create a custom validator with a function attached inside the language file (in this case jquery.validationEngine-en.js):

    "notEqual":  {
        "func": function(field, rules, i, options){
            return (field.val() == $('#username').val()) ? false : true;
        },
        "alertText": "* Username and password must be different"
    },
    

    In my html markup, I use it like this:

    <input type="hidden" name="username" value="yourPassword" id="username"/>
    <input class="validate[custom[notEqual]]" type="password" name="confirmPassword" value=""/>
    

    Hope that helps someone.