JavaScript Forms and Validation

Form validation means checking what the visitor typed before it is sent. JavaScript gives quick feedback, so the visitor can fix a mistake at once.

<form id="signup">
  <input type="text" id="name" placeholder="Name">
  <input type="email" id="email" placeholder="Email">
  <p id="error" style="color:red"></p>
  <button type="submit">Sign up</button>
</form>
const form = document.getElementById("signup");
const error = document.getElementById("error");

form.addEventListener("submit", (event) => {
  const name = document.getElementById("name").value.trim();
  const email = document.getElementById("email").value.trim();
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (name === "") {
    error.textContent = "Please enter your name";
    event.preventDefault();          // stop sending
  } else if (!emailPattern.test(email)) {
    error.textContent = "Please enter a valid email";
    event.preventDefault();
  } else {
    error.textContent = "";
  }
});
  • Read the value with input.value, and clean it with trim().
  • Listen to the form’s submit event, not to the click of the button, so Enter key also works.
  • Call event.preventDefault() when the data is wrong.
  • The regular expression only checks the shape of an email. See Regular Expressions.

If the name is empty, the paragraph shows:

Output of the above program is

Please enter your name


HTML5 validation (use it first)

HTML attributes like required, type="email", minlength and pattern do the basic checks without any JavaScript.

<input type="email" required>
<input type="text" minlength="3" required>

With JavaScript you can ask the form if it is valid, and show your own message:

const email = document.getElementById("email");
console.log(email.checkValidity());        // true or false
email.setCustomValidity("Use your office email");
Note: Validation in JavaScript can be skipped by anyone (they can switch off JavaScript). Always check the data again on the server. See HTML Forms.

Summary

  • Use the submit event and preventDefault() for wrong data.
  • Show clear error messages near the field.
  • Use HTML5 validation first and always validate on the server too.
  • Next: Callbacks and Promises.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a JavaScript program to change the text of a paragraph on button click
Write a JavaScript program to switch dark mode on and off
Interview Questions & Answers
What is the DOM in JavaScript?
How do you select elements in the DOM?
What are events and event listeners in JavaScript?
What is event bubbling and capturing in JavaScript?
What is event delegation in JavaScript?