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

前端 未结 9 868
小鲜肉
小鲜肉 2020-11-28 03:23

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

相关标签:
9条回答
  • 2020-11-28 03:58

    I propose a multi-valued function...

    jQuery.validator.addMethod("notEqualTo",
    function(value, element, param) {
        var notEqual = true;
        value = $.trim(value);
        for (i = 0; i < param.length; i++) {
            if (value == $.trim($(param[i]).val())) { notEqual = false; }
        }
        return this.optional(element) || notEqual;
    },
    "Please enter a diferent value."
    );
    

    And I call it...

    $("#abm-form").validate({
    debug: true,
    rules: {
        password1: {
            required: true,
            minlength: 10,
            notEqualTo: ['#lastname', '#firstname', '#email']
        },
        password2: {
            equalTo: '#password1'
        }
    }
    });
    

    This works for me!

    0 讨论(0)
  • 2020-11-28 03:58

    Thanks for @Nick Craver♦'s answer, but in my working environment, it needs to be slightly modified before it could work.

     $.validator.addMethod("notEqualTo", function(value, element, param) {
           return this.optional(element) || value != $(param).val();
     }, 'This two elements are the same, please change it.');
    
    0 讨论(0)
  • 2020-11-28 03:59

    There's one called "notEqualTo" in additional-methods.js in the download package:

    https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/notEqualTo.js

    0 讨论(0)
提交回复
热议问题