5

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!

Mark Hardin
  • 527
  • 1
  • 7
  • 15

3 Answers3

9

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...

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Just a couple of issues with the example provided: 1. There's a missing ')' on the `if` statement. 2. `$.inArray()` returns the index of the value it's looking for, i.e. if a value is not found the result will be -1. The if statement should therefore be `if ( $.inArray( value, values ) > -1 ) {` otherwise -1 and 0 results will produce incorrect results when converted to true/false. – Adam Westbrook Nov 13 '13 at 11:04
5
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

ilyes kooli
  • 11,959
  • 14
  • 50
  • 79
1

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.');
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337