Categories
JavaScript Answers

How to Set Custom HTML5 Required Field Validation Message with JavaScript?

Spread the love

We can set custom HTML5 required field validation messages with the setCustomValidity method.

For instance, if we have the following input:

<form>
  <input type="email" pattern="[^@]*@[^@]" required  />
  <input type="submit" />
</form>

Then we can set a custom validation message by writing:

const input = document.querySelector('input')
input.addEventListener('invalid', (e) => {
  e.target.setCustomValidity('Put here custom message')
})

We get the input with document.querySelector .

Then we listen to the invalid event with addEventListener .

Then we call e.target.setCustomValidity on it with our own validation error message.

e.target is the input element since we called addEventListener on the input .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *