prevent Duplicate values using Jquery Validation

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/


Something like this should work:

$(function(){

$('input[name^="text"]').change(function() {

    var $current = $(this);

    $('input[name^="text"]').each(function() {
        if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id'))
        {
            alert('duplicate found!');
        }

    });
  });
});

In a nutshell, how this works is: Whenever a user enters something into a text box, JQuery loops through all the text boxes in the form and compares their values with the value that the user just entered, if a duplicate value is found, then alert the user.

Tags:

Jquery