How to set custom validation messages for HTML forms?

Here is some code to display a custom error message:

<input type="text" id="username" required placeholder="Enter Name"
       oninvalid="ths.setCustomValidity('Enter User Name Here')"
       oninput="setCustomValidity('')"/>

This part is important because it hides the error message when the user inputs new data:

oninput="setCustomValidity('')"

Note: the this keyword is not required for inline event handlers, but you may want to use it anyway for consistency.

Leave a Comment