Skip to content

Instantly share code, notes, and snippets.

@NimzyMaina
Last active June 20, 2019 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NimzyMaina/b97852a5adee45334b25503965f1b68f to your computer and use it in GitHub Desktop.
Save NimzyMaina/b97852a5adee45334b25503965f1b68f to your computer and use it in GitHub Desktop.
Jquery validation unique from other input (use class to differentiate)
jQuery.validator.addMethod("notEqualToGroup", function (value, element, options) {
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function () {
thisVal = $(this).val();
if (thisVal == valueToCompare) {
matchesFound++;
}
});
// count should be either 0 or 1 max
if (this.optional(element) || matchesFound <= 1) {
//elems.removeClass('error');
return true;
} else {
//elems.addClass('error');
}
}, jQuery.format("Please enter a Unique Value."))
@NimzyMaina
Copy link
Author

NimzyMaina commented Jul 18, 2017

This is used by jquery validator to ensure unique fields in a form

Simply add a class to the input field to differentiate them. Then in the validation rules add this

phone: {
      required: true,
      notEqualToGroup: ['.distinctphones']
   }

@acmr93
Copy link

acmr93 commented Jun 17, 2019

Ty

@NimzyMaina
Copy link
Author

You are welcome @acmr93

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment