HTML5 Form Validation With Custom Message – Programming Code Examples

HTML5 Form Validation With Custom Message2 min read

Change or remove HTML5 form validation default error messages

Let’s say we have a form with a required input, like this:

If you try to submit such a form without filling out the required field, you would be stopped by the browser with an error message, like this:

That’s a very generic message. It has different text and different look between different browsers. It will be in the language of the user’s system or browser, not the language of your website.

For those reasons, you might want to change those error messages. And you can!

How to customize built-in form validation error messages

  1. Grab the input element(s) with a querySelector/querySelectorAll.
  2. Add an event listener for the invalid event.
    1. When handling the event, under, you’ll get the validity state of the input. For example, for a required input that was not filled out, will be true.
    2. You can call setCustomValidity on the input element to provide a custom error message.
  3. Add an event listener for the change event to reset the custom error when the input value changes.

Example code

See this GitHub gist for a full index.html file.

On line 4, there’s no need to check if the input is required because is only going to be set to true for required inputs.

Explicitly resetting custom validity to an empty string when the input value changes is necessary. Without it, if a mistake has been made once, you wouldn’t be able to submit the form at all.

Validity state

The object looks like this:

Check out the MDN docs about ValidityState to learn how the keys in map to specific validation features.


Leave a Comment