Skip to content Skip to sidebar Skip to footer

How To Verify That Email Addresses Are Unique

I have a form containing 10 to 15 email addresses. How can I check whether all addresses are unique? And how can I determine which ones are duplicates? I'm looking for a JavaScript

Solution 1:

To find duplicates in an array, insert the elements into a dictionary that keeps track of the number of times each element appears. Then each element with a count greater than 1 is a duplicate.

Demonstration:

function findDuplicates(data) {
  var counts = {};
  data.forEach(function (item) {
    if (counts[item] === undefined) {
      counts[item] = 1;
    } else {
      counts[item] += 1;
      if (counts[item] == 2) {
        print('duplicate: ' + item);
      }
    }
  });
}

function print(s) {
  document.write(s + '<br />');
}

var addresses = ['abc@xyz.com', 'foo@bar.com', 'abc@xyz.com', 'babar@elephants.com', 'president@whitehouse.gov', 'babar@elephants.com', 'abc@xyz.com'];
findDuplicates(addresses);

Solution 2:

You can use an array of emails and the jQuery statment inArray like so:

function validateEmails() {
    var emailArray = ["email1", "email2", "email3", "email4"];
    var outputArray = [];
    for (int i = 0; i < emailArray.length; i++) {
        if($.inArray(emailArray[i], outputArray) != -1) {
            //item is not in array, add it
            outputArray.push(emailArray[i]);
        } else {
            //item is a duplicate
            alert("This is the duplicate email id:" + emailArray[i]);
        }
    }
}

Essentially, you just would read each of the email ids you have into an array, emailArray. Then, you would loop through each object. If $.inArray does not return -1, then the item is a duplicate, and the window would alert the user of the specified id.


Post a Comment for "How To Verify That Email Addresses Are Unique"