prevent Duplicate values using Jquery Validation

前端 未结 11 1878
深忆病人
深忆病人 2020-12-04 22:28

I have form and form text field which generates dynamically using JSP. And I\'m using Jquery validation but want to add functionlaty to prevent duplicate entry in the form.<

11条回答
  •  -上瘾入骨i
    2020-12-04 22:57

    I'm pretty new to jquery validation, but I had a similar issue to solve, I came up with the following solution (using previous answers for inspiration!):

    Javascript:

    jQuery.validator.addMethod("unique", function(value, element, params) {
        var prefix = params;
        var selector = jQuery.validator.format("[name!='{0}'][unique='{1}']", element.name, prefix);
        var matches = new Array();
        $(selector).each(function(index, item) {
            if (value == $(item).val()) {
                matches.push(item);
            }
        });
    
        return matches.length == 0;
    }, "Value is not unique.");
    
    jQuery.validator.classRuleSettings.unique = {
        unique: true
    };
    

    Usage:

    
    
    

    Demo here: http://jsfiddle.net/mysteryh/bgzBY/

提交回复
热议问题