Sometimes, we want to set custom validation message for HTML5 form required attribute with JavaScript.
In this article, we’ll look at how to set custom validation message for HTML5 form required attribute with JavaScript.
How to set custom validation message for HTML5 form required attribute with JavaScript?
To set custom validation message for HTML5 form required attribute with JavaScript, we call the setCustomValidity method.
For instance, we write
<input
  type="text"
  id="username"
  required
  placeholder="Enter Name"
  oninvalid="this.setCustomValidity('Enter User Name Here')"
  oninput="this.setCustomValidity('')"
/>
to call setCustomValidity with the validation message we want to show.
oninput is run as we type and oninvalid is run when the input is invalid.
Conclusion
To set custom validation message for HTML5 form required attribute with JavaScript, we call the setCustomValidity method.
