Validate HTML Form Inputs With Vanilla Js

Lukas Mauser - Oct 9 '23 - - Dev Community

Validating HTML forms can be a pain >.<

You might be tempted to pull in an external form library, but the fact that you need to deal with a few input fields that require custom validation is probably not enough reason to pull in an external library.

Each external library introduces new dependencies and potential vulnerabilities. It comes with a learning curve and sometimes these form libraries do not really help a lot to tidy your code. On top you either need to customize the layout so much that you did not save anything at the end or you're stuck with their design...

Vanilla JS and HTML offer some great tools already!

Let me show you, how you can easily add custom validation to your HTML forms.

In our example, we have an HTML form that contains two password input fields:

<form>
  <input id="password" type="password" placeholder="password" />
  <input id="confirmPassword" type="password" placeholder="confirm password" />
  <button type="submit">Sign up</button>
</form>
Enter fullscreen mode Exit fullscreen mode

We can add basic validation with built in HTML attributes like required or minlength.:

  <input id="password" type="password" placeholder="password" required  minlength="6" />
Enter fullscreen mode Exit fullscreen mode

But what if we want to check, if the password and confirm password field match?

For this scenario, we need custom validation.

So let's explore how easy it is, to write a custom validation function:

function formSubmitHandler() {
  // grab inputs
  const passwordInput = document.getElementById("password");
  const confirmPasswordInput = document.getElementById("confirmPassword");

  // validation logic
  if (passwordInput.value !== confirmPasswordInput.value) {
    confirmPasswordInput.setCustomValidity("The passwords don't match!");
    confirmPasswordInput.reportValidity();
    return;
  }
  // handle valid inputs ...
}
Enter fullscreen mode Exit fullscreen mode

First, we simply grab our inputs with document.getElementById(...). Then we run our custom validation logic on the input values. If the validation fails, we set a custom validation error message on the input via the setCustomValidity(...) function and trigger the validation event with the reportValidity() function.

And that's all it takes. If necessary you can even translate your validation messages and structure your code as you need to.

In simple use cases you don't need to add an external form library to handle validation for your form fields.

Take note though, that cross-browser support for these built in validation methods should be double checked.

. . . . . . . .
Terabox Video Player