Inline validation for invalid e-mail fields



You can try out the code yourself by running code in the console.

Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) to open the chrome console.

Copy the code into the console and press enter to see the changes.


JavaScript

// We start by storing the form and e-mail field into a variable.
const form = document.getElementById("form");
const emailField = document.getElementById("email");

// A basic regular expression to check e-mail validity.
function checkIfEmailValid(email) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
    return true;
  } else {
    return false;
  }
}

// This function adds the error the the input
function addInlineError(input, text) {
  input.style.borderColor = "red";
  document.getElementById("emailLabel").innerText = text;
  disableSubmit();
}

// This function adds the error the the input
function resetError(input) {
  input.style.borderColor = "black";
  document.getElementById("emailLabel").innerText = "";
  enableSubmit();
}

// This function disables the submit
function disableSubmit() {
  document.getElementById("submit").setAttribute("disabled", "disabled");
}

// This function enables the submit.
function enableSubmit() {
  document.getElementById("submit").removeAttribute("disabled");
}

// When you input an e-mail that is wrong we throw an error we also check for an empty field.
emailField.addEventListener("focusout", (event) => {
  if (emailField.value === "") {
    addInlineError(emailField, " Empty field");
  } else if (checkIfEmailValid(emailField.value) === false) {
    addInlineError(emailField, " Invalid e-mail");
  } else {
    resetError(emailField);
  }
});

// When you start correcting the form we reset the error.
emailField.addEventListener("focusin", (event) => {
  resetError(emailField);
});