How do I validate an array of email addresses in JavaScript?
Alex K
alex k profile pic

Validating an array of email addresses in JavaScript involves checking each email address against a regular expression pattern that conforms to the email format. Here's an example of how you can validate an array of email addresses:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function validateEmails(emails) {
  const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  const invalidEmails = [];

  for (let i = 0; i < emails.length; i++) {
    const email = emails[i];
    if (!emailRegex.test(email)) {
      invalidEmails.push(email);
    }
  }

  return invalidEmails;
}

In this example, thevalidateEmails function takes an array of email addresses,emails, as input. It initializes a regular expression pattern,emailRegex, which matches the common structure of email addresses. Within the function, a loop is used to iterate through each email address in theemails array. Thetest() method of the regular expression pattern is used to check if each email address matches the pattern. If an email address does not match the pattern, it is considered invalid and added to theinvalidEmails array. Finally, theinvalidEmails array is returned, which contains all the invalid email addresses. Here's an example usage of thevalidateEmails function:

1
2
3
4
5

const emails = ['test@example.com', 'invalid-email', 'another@example.com'];
const invalidEmails = validateEmails(emails);

console.log(invalidEmails); // Output: ['invalid-email']

In this example, theemails array contains three email addresses. ThevalidateEmails function is called to validate these email addresses. TheinvalidEmails array will contain the invalid email address'invalid-email'. It's important to note that email validation using regular expressions can have limitations and may not catch all possible edge cases. Email address formats can vary, and the only way to ensure complete validation is to send a verification email and confirm the address's existence. Additionally, remember that client-side email validation is useful for improving user experience by catching obvious errors early. However, server-side validation is essential for security and ensuring data integrity.