4Jean 4Jean - 5 months ago 66
jQuery Question

JQuery Validation for Duplicates in Form Array

I want to display error for values that are duplicates or not unique, but my form takes in array of inputs, I have checked these questions on jsfiddle,

name = "week[]"
fails but
name = "week"
works fine


  1. Question 1

  2. Question 2

  3. Question 3

  4. Question 4



Form HTML

I tried this

<script type="text/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
};
</script>


Any help is appreciated

Answer

You can create array of input values with map() and then check for duplicates in array and show/hide error message

$('#myForm input').on('change', function() {

  //Create array of input values
  var ar = $('#myForm input').map(function() {
    if ($(this).val() != '') return $(this).val()
  }).get();

  //Create array of duplicates if there are any
  var unique = ar.filter(function(item, pos) {
    return ar.indexOf(item) != pos;
  });

  //show/hide error msg
  (unique.length != 0) ? $('.error').text('duplicate'): $('.error').text('');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
  <input type="number" name="week[]" id="week1">
  <input type="number" name="week[]" id="week2">
  <input type="number" name="week[]" id="week3">
  <input type="number" name="week[]" id="week4">
</form>
<div class="error"></div>

Comments