Next.js starter your AI actually understands. Ship internal tools in days not weeks. Pre-order $199 $499 → [Get it now]

How to validate email in JavaScript

Email validation is a critical part of form handling in web applications, preventing invalid data from being submitted and improving user experience with immediate feedback. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented email validation in countless forms across admin panels and user interfaces. From my expertise, the most practical approach is to use a regular expression that balances accuracy with simplicity, covering the vast majority of valid email formats. This method is fast, requires no external libraries, and works consistently across all browsers.

Use a regex pattern with the test() method to validate email addresses in JavaScript.

const isValidEmail = (email) => {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return regex.test(email)
}

console.log(isValidEmail('[email protected]'))  // true
console.log(isValidEmail('invalid.email'))     // false

How It Works

The regex pattern /^[^\s@]+@[^\s@]+\.[^\s@]+$/ checks for a basic email structure: one or more characters before @, followed by one or more characters, a dot, and one or more characters after the dot. The test() method returns true if the email matches this pattern, and false otherwise. This pattern catches most common email format errors while remaining simple and performant.

More Comprehensive Email Validation

For stricter validation that handles more edge cases:

const isValidEmail = (email) => {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return regex.test(email)
}

console.log(isValidEmail('[email protected]'))  // true
console.log(isValidEmail('invalid@'))                      // false
console.log(isValidEmail('@example.com'))                  // false

This pattern is more restrictive, allowing only alphanumeric characters and specific symbols in the local part (before @), alphanumeric characters and hyphens in the domain, and requiring at least two letters in the top-level domain. It rejects emails with missing parts or invalid characters.

HTML5 Email Validation

Leverage the browser’s built-in validation with HTML5 input type:

const validateEmailWithHTML5 = (email) => {
  const input = document.createElement('input')
  input.type = 'email'
  input.value = email
  return input.checkValidity()
}

console.log(validateEmailWithHTML5('[email protected]'))  // true
console.log(validateEmailWithHTML5('invalid'))            // false

Creating a temporary input element with type="email" and using checkValidity() delegates validation to the browser’s built-in rules. This approach follows the HTML5 specification and handles complex email formats that simple regex might miss. The browser’s validation is well-tested and updated to handle edge cases.

Real-Time Email Validation

Provide immediate feedback as users type in a form:

const emailInput = document.getElementById('email')
const errorMessage = document.getElementById('error')

emailInput.addEventListener('input', (e) => {
  const email = e.target.value
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

  if (email && !regex.test(email)) {
    errorMessage.textContent = 'Please enter a valid email address'
    emailInput.classList.add('invalid')
  } else {
    errorMessage.textContent = ''
    emailInput.classList.remove('invalid')
  }
})

This code validates on every keystroke, showing an error message when the email format is invalid. The check email && !regex.test(email) ensures validation only runs when there’s content, avoiding showing errors for empty fields. The invalid class can style the input with a red border or other visual indicator.

Validating on Form Submit

Validate email when the form is submitted:

const form = document.getElementById('signup-form')

form.addEventListener('submit', (e) => {
  e.preventDefault()

  const email = document.getElementById('email').value
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

  if (!regex.test(email)) {
    alert('Please enter a valid email address')
    return
  }

  // Proceed with form submission
  console.log('Email is valid, submitting form...')
})

Preventing default submission with e.preventDefault() allows you to run validation first. If the email is invalid, show an error and stop the submission. If valid, proceed with your submission logic, such as sending data to an API.

Checking Email Domain

Validate specific email domains for business applications:

const isCompanyEmail = (email) => {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

  if (!regex.test(email)) {
    return false
  }

  const domain = email.split('@')[1]
  const allowedDomains = ['company.com', 'example.org']

  return allowedDomains.includes(domain)
}

console.log(isCompanyEmail('[email protected]'))    // true
console.log(isCompanyEmail('[email protected]'))       // false

After validating the basic format, extract the domain using split('@')[1] and check if it’s in your allowed list. This is useful for restricting signups to specific organizations or verifying business email addresses.

Using a Validation Library

For production applications with complex validation needs, consider using a validation library:

import { z } from 'zod'

const emailSchema = z.string().email()

try {
  emailSchema.parse('[email protected]')
  console.log('Valid email')
} catch (error) {
  console.log('Invalid email:', error.errors[0].message)
}

Libraries like Zod provide robust, well-tested validation with clear error messages. The email() method applies comprehensive email validation rules that handle edge cases beyond what simple regex can cover. This approach is especially valuable in TypeScript projects where Zod also provides type inference.

Best Practice Note

This is the same email validation approach we use in CoreUI form components to provide instant feedback and prevent invalid submissions. For client-side validation, combine basic format checking with user-friendly error messages. Always validate on the server side as well, since client-side validation can be bypassed. For additional security measures, see our guide on how to prevent XSS attacks in JavaScript to sanitize user input. For production forms, consider using CoreUI’s CFormInput component which includes built-in validation styling and feedback. Remember that perfect email validation is impossible with regex alone - the only way to truly verify an email is to send a confirmation message to it.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author