Categories
JavaScript Answers

How to set custom HTML5 required field validation message with JavaScript?

Spread the love

Sometimes, we want to set custom HTML5 required field validation message with JavaScript.

In this article, we’ll look at how to set custom HTML5 required field validation message with JavaScript.

How to set custom HTML5 required field validation message with JavaScript?

To set custom HTML5 required field validation message with JavaScript, we can call the setCustomValidity method.

For instance, we write

<input type="text" name="email" id="emailElement" required />

to add an input element.

Then we write

const emailElement = document.getElementById("emailElement");

emailElement.addEventListener(
  "invalid",
  (e) => {
    const message = `${e.target.value}is not a valid email address`;
    emailElement.setCustomValidity(message);
  },
  false
);

to select the input with getElementById.

And then we call emailElement.addEventListener to listen for the invalid event.

In the event callback, we call emailElement.setCustomValidity with the validation error message.

Conclusion

To set custom HTML5 required field validation message with JavaScript, we can call the setCustomValidity method.

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 *