How to add a Not Equal To rule in jQuery.validation

Viewed 89344

I was wondering how to make it so that I could make a rule where a field is not equal to a value. Like I have a field called 'name' so I don't want 'name' = 'Your Name.'

Does anybody have an idea of how to do this? thanks for any help.

9 Answers

Taking some great examples here, I wrote another version that works with multiple field to check against

/*=====================================================*/
/* Jquery Valiation addMethod*/
/* Usage:  password: {notEqualTo: ['#lastname', '#firstname', '#email']} */
/*====================================================*/
jQuery.validator.addMethod("notEqualTo",
    function (value, element, param) {
        var notEqual = true;
        value = $.trim(value);
        for (i = 0; i < param.length; i++) {

            var checkElement = $(param[i]);
            var success = !$.validator.methods.equalTo.call(this, value, element, checkElement);
            // console.log('success', success);
            if(!success)
                notEqual = success;
        }

        return this.optional(element) || notEqual;
    },
    "Please enter a diferent value."
);
/*=====================================================*/
/*=====================================================*/

Usage

    $("form").validate(
        {
            rules: {
                passwordNewConfirm: {equalTo: "#passwordNew"},
                passwordNew: { notEqualTo: "#password" },
                password: { notEqualTo: ['#passwordNew', '#passwordNewConfirm'] }
            },
        });
Related