简体   繁体   中英

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. I assume that I could use a 'keyup' function but I'm not sure. I'm trying to use jQuery validate but can only get it working for two fields at a time. Is this possible with jQuery or maybe there is a better solution? Angular?

Give all the fields a class like 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

https://jqueryvalidation.org/equalTo-method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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