Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent Duplicate values using Jquery Validation

Tags:

jquery

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.

like image 864
Vicky Avatar asked Jun 02 '10 06:06

Vicky


People also ask

How to avoid duplicate values in JQuery?

var seen = {}; $('a'). each(function() { var txt = $(this). text(); if (seen[txt]) $(this). remove(); else seen[txt] = true; });

How can check duplicate value in textbox using JQuery?

var $inputsWithSameValue = $('input[value=' + $(this). val() + ']'); hasDuplicates = $inputsWithSameValue.


1 Answers

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/

like image 98
MysteryH Avatar answered Sep 23 '22 21:09

MysteryH