简体   繁体   English

如何使用jQuery验证多个相同的输入字段?

[英]How to validate multiple identical input fields with jQuery?

I have six input fields in form and I need to do some validation to make sure that none of them are identical in real time. 我有六个输入字段,需要进行一些验证以确保它们中的所有字段都不是实时相同的。 For example if a user try's to enter a duplicate field jQuery would prompt the user that they must enter unique fields, before even submitting the form. 例如,如果用户尝试输入重复字段,则jQuery会提示用户必须输入唯一字段,甚至不提交表单。 I assume that I could use a 'keyup' function but I'm not sure. 我假设我可以使用“ keyup”功能,但不确定。 I'm trying to use jQuery validate but can only get it working for two fields at a time. 我正在尝试使用jQuery validate,但一次只能将其用于两个字段。 Is this possible with jQuery or maybe there is a better solution? 使用jQuery是否可能,或者有更好的解决方案? Angular? 有角吗?

Give all the fields a class like class="alldifferent" . 给所有字段一个类,例如class="alldifferent" Then you can use: 然后,您可以使用:

$(".alldifferent").keyup(function() {
    var val = $(this).val();
    if (val != '') {
        $(".alldifferent").not(this)).each(function() {
            if ($(this).val() == val) {
                alert("Error, duplicate value " + val);
                return false; // stop the loop
            }
        });
    }
});

The Jquery Validation work on submit from you can use keyup function see in documentation 您可以使用keyup函数进行关于提交的Jquery验证工作,请参阅文档

https://jqueryvalidation.org/equalTo-method https://jqueryvalidation.org/equalTo-method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM