Form Validation

Let's learn different strategies to validate the data entered by the user.

Checking data inputted by users before it gets sent to a server is a major use of JavaScript with web forms. Using form validation, you can improve the user’s experience by immediately alerting him on problems with their input. This is also an efficient way to prevent useless server requests with wrong data.

Validation can happen in several ways:

  • as input is being entered
  • after input is entered
  • when the user submits the form. This last technique only involves adding validation in the submit event handler for the form: you already know how to do that. We’ll look at the other two techniques one at a time, using the same example form as before.

Instant validation

Validation, while a user is inputting information, is based on input events, which are triggered on an input zone each time its value changes.

The following code example adds an input event handler on the password field. This handler checks the length (number of characters) of the password being typed and shows a message to the user with specific content and color.

Get hands-on with 1200+ tech skills courses.