Author -  Sai gowtham

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.

HTML5 validation error message

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.

html5 custom validation message

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY