How to Set a Custom Validation Message in HTML5
In this tutorial, we are going to learn about how to set a custom validation message for HTML5 form (input) elements.
HTML5 provides us built-in form validation, instead of depending on scripts we can validate any input field by just using a required
attribute.
Let’s see an example:
<form>
<input type="email" placeholder="Email" required/>
<input type="submit"/>
</form>
Now, if we type the incorrect email address we’ll see an error message generated by the built-in validation.
Setting Custom validation message
There are some drawbacks of using built-in validation messages.
-
The message will depend on a browser we are using.
-
They also depend on the browser locale, it means if you have a page in one language, but the error message is displayed in another language.
To set a custom validation message we need to use JavaScript and HTML5 constraint validation API.
<form>
<input type="email" placeholder="Email" id="email" required />
<input type="submit" id="submit"/>
</form>
const email = document.querySelector('#email');
const submit=document.querySelector('#submit');
submit.addEventListener('click',()=>{
if(email.validity.typeMismatch){
email.setCustomValidity('Please enter correct email');
}else{
email.setCustomValidity('');
}
})
In the above code first, we checked if email
has any typeMismatch
if there is a mismatch we have set a custom message using the setCustomValidty()
method else we removed the custom message by calling the setCustomValidity()
method again with an empty string.