« back

Enforcing Uniqueness with JQuery Validation

09 Oct 2012

When there is no go to way to do something you need to, you have to make it yourself.

Here was the problem. I had a group of text inputs that each needed to take a number 1-6 but the number needed to be unique to the group. Using the JQuery Validation Plugin I was easily able to require that the box was filled in using the required method. I was also easily able to enforce that the number was 1-6 using the range method. Making sure that the number was unique required a little more TLC.

I needed a way to check if the value the user was entering was unique. I gave all of the elements in that group a class. I first created an array out of all the elements in that class.

1     $.validator.addMethod('unique', function (enteredValue) {
2     	var inputArray = $('.number_rank').map(function() { return $(this).val(); });
3     

Then I used a function to count the amount of times the entered value was in the input array.

1     function countElement(item,array) {
2         var count = 0;
3         $.each(array, function(i,v) { if (v === item) count++; });
4         return count;
5     }
6     

I then tied that function into my uniqueness method like this.

1     $.validator.addMethod('unique', function (enteredValue) {
2     	var inputArray = $('.number_rank').map(function() { return $(this).val(); });
3     	var occurrence = countElement(enteredValue, inputArray);
4     	return !(occurrence >= 2 );
5     });
6     

The final solution all together looks like this.

 1     $.validator.addMethod('unique', function (enteredValue) {
 2     	var inputArray = $('.number_rank').map(function() { return $(this).val(); });
 3     	var occurrence = countElement(enteredValue, inputArray);
 4     	return !(occurrence >= 2 );
 5     });
 6 
 7     function countElement(item,array) {
 8         var count = 0;
 9         $.each(array, function(i,v) { if (v === item) count++; });
10         return count;
11     }
12     

comments powered by Disqus