如何在 jQuery.validation 中添加 Not Equal To 规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3571347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:41:33  来源:igfitidea点击:

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

jqueryvalidation

提问by Kyle Hotchkiss

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.'

我想知道如何制作它以便我可以制定一个字段不等于值的规则。就像我有一个名为“name”的字段,所以我不想要“name”=“Your Name”。

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

有没有人知道如何做到这一点?谢谢你的帮助。

回答by Nick Craver

You could use a custom method, something like this:

您可以使用自定义方法,如下所示:

jQuery.validator.addMethod("notEqual", function(value, element, param) {
  return this.optional(element) || value != param;
}, "Please specify a different (non-default) value");

Then use it like this:

然后像这样使用它:

$("form").validate({
  rules: {
    nameField: { notEqual: "Your Name" }
  }
});

Adding it as a rule like this makes it more extensible, so you can use it to compare against the default value in other fields.

将其添加为这样的规则使其更具可扩展性,因此您可以使用它来与其他字段中的默认值进行比较。

回答by Frank Luke

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.

如果问题是关于将referralsales 与2 个不同的基础(比如#initialContact 和#salesperson)进行比较,那么只需将该规则添加到列表中即可。

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

回答by Jose

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!

这对我有用!

回答by TrueWill

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

下载包中的 additional-methods.js 中有一个叫做“notEqualTo”:

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

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

回答by Richard L

Not sure if you got your answer but:

不确定你是否得到了答案,但是:

return this.optional(element) || value != param;

返回 this.optional(element) || 值!=参数;

won't work if the value is variable.

如果值是可变的,则不起作用。

It needs to read:

它需要阅读:

return this.optional(element) || value != $(param).val();

返回 this.optional(element) || 值 != $(param).val();

Cheers

干杯

回答by Robert

If you have just one value where you want it to not be like your question implies, you can check against that pretty easily without any external plugins.

如果您只有一个值,您希望它不像您的问题所暗示的那样,您可以很容易地进行检查,而无需任何外部插件。

$('#yourForm').submit(function(e) {
    if ( $('input[name="yourField"]').val()=='Your Name' )
        e.preventDefault();
        alert("Your message here");
    }
});

回答by Sasha.M

Thanks a lot, Nick !!! A little adding: if you have a few fields to validate into validate() function, the syntax should be :

非常感谢,尼克!!!一点补充:如果你有几个字段要验证到 validate() 函数中,语法应该是:

self.logo.rules(
    'add', {
       notEqual: "Select the Logo"
     }
);

回答by Xiao Ai

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

感谢@Nick Craver? 的回答,但在我的工作环境中,它需要稍作修改才能工作。

 $.validator.addMethod("notEqualTo", function(value, element, param) {
       return this.optional(element) || value != $(param).val();
 }, 'This two elements are the same, please change it.');

回答by Ravi Ram

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'] }
            },
        });