Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

prevent Duplicate values using Jquery Validation

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.

E.g.

<form name="myForm" id="myForm">
      <input type="text" name="text1" id="text1">
      <input type="text" name="text2" id="text2">
      <input type="text" name="text3" id="text3">
      =
      = 
      N number of form fields
      <input type="text" name="textn" id="textn">

</form>

I want to check if there is any duplicate value entered in the textfield using jQuery validation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<input name="currency1" unique="currency" />
<input name="currency2" unique="currency" />

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...