HTML5 Form Validation With Custom Message – Programming Code Examples
HTML

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 event.target.validity, you’ll get the validity state of the input. For example, for a required input that was not filled out, event.target.validity.valueMissing 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 event.target.validity.valueMissing 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 event.target.validity object looks like this:

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

Source: https://angelika.me/2020/02/01/custom-error-messages-for-html5-form-validation/

Leave a Comment