I have a form with a dozen email input fields and each email needs to be unique. What is the most elegant way via jquery to perform the comparison among all the fields without manually writing all the comparisons like below:
if($("#email1").val() == $("#email2").val() || ....) {
isValid = false;
alert("emails must be unique.");
}
Thanks in advance!
The simplest way is to put the emails into a Set
, and compare its size:
const $inputs = $('input[id^=email]');
const uniques = new Set($input.map((i, el) => el.value).get());
if (uniques.size < $inputs.length) {
alert('Emails must be unique.');
}
If you can't use ES6 (or other modern JS features), use jQuery's inArray:
var values = [];
$('input[id^=email]').each(function () {
if ($.inArray(this.value, values) >= 0) {
alert('Emails must be unique.');
return false; // <-- stops the loop
}
values.push(this.value);
});
If that selector is too broad, you can specify your IDs in a comma separated list, like this:
$('#email1, #email2, #email3') // ...and so on
or just add a class to all the elements you want to select...
var duplicate=false;
$('input[id^=email]').each(function(){
var $this = $(this);
if ($this.val()===''){ return;}
$('input[id^=email]').not($this).each(function(){
if ( $(this).val()==$this.val()) {duplicate=true;}
});
});
if(duplicate) alert('email must be valid');
DEMO
Try adding a unique
to all the classes you want to be unique, add thier values to an array, and then check to see if the array has only unique values.
<input type="text" class="unique" id="email1" />
<input type="text" class="unique" id="email2" />
Then using jQuery:
var values = $('input.unique').map(function(){
return $(this).val();
}).get();
Then check if the array is unique:
var uniqueValues = $.grep(values, function (v, k) {
return $.inArray(v, values) === k;
});
if(uniqueValues.length !== values.length){
alert('emails must be unique.');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With