how to create an email validation in javascript

To create an email validation in JavaScript, you can use regular expression to match the email pattern. Here's a sample code using regex in JavaScript to validate email:

index.tsx
function validateEmail(email) {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return regex.test(email);
}
130 chars
5 lines

Here we use the test() method of the regular expression to see if the input email matches the pattern.

To implement this validation in a front-end form, we can add an onsubmit event listener to the form, and call this function on form submission:

<form onsubmit="return validateForm()">
  <input type="email" id="email" name="email">
  <input type="submit" value="Submit">
</form>

<script>
  function validateForm() {
    const emailInput = document.getElementById("email").value;
    if (!validateEmail(emailInput)) {
      alert("Please enter a valid email address.");
      return false;
    }
    // form submission logic here
  }
</script>
399 chars
16 lines

This will prevent the form from submitting if the email entered is not valid, and show a message to the user prompting them to enter a valid email address.

gistlibby LogSnag