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

前端 未结 9 954
小鲜肉
小鲜肉 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:36

    Nick's answer fits the bill. I needed to compare two fields on the form and make sure they were not equal. I modified it just a bit.

    jQuery.validator.addMethod("notEqual", function(value, element, param) {
     return this.optional(element) || value != $(param).val();
    }, "This has to be different...");
    
    $("#cform").validate(
    {
        rules: {
            referringsales: { required: false, notEqual: "#salesperson" }
        }
    });
    

    Edited to answer comment:

    If you have more than one set of dropdowns to compare, the method also works with that case.

    jQuery.validator.addMethod("notEqual", function(value, element, param) {
     return this.optional(element) || value != $(param).val();
    }, "This has to be different...");
    
    $("#cform").validate(
    {
        rules: {
            referringsales: { required: false, notEqual: "#salesperson" }
            DropDown2: { required: false, notEqual: "#SecondBase" }
        }
    });
    

    If the question is regarding comparing referringsales against 2 different bases (say #initialContact and #salesperson), then simply add that rule to the list.

    referringsales: { required: false, notEqual: "#salesperson", notEqual: "#initialContact" }
    

提交回复
热议问题