How to manually show a HTML5 validation message from a JavaScript function?

I want to know if there is any way to programatically show a HTML5 validation error, using a JavaScript function.

This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.

I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).


HTML Form:

    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>

<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>


function triggerCustomMsg()
    document.getElementById("email").setCustomValidity("This email is already used");


The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.



You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.


This question was asked over a year ago, but it's a good question that I recently encountered as well...

My solution was to use JavaScript to create an attribute (I went with "data-invalid") on the <label> of each <input>, <select> and <textarea> containing the validationMessage.

Then some CSS...

label:after {
    content: attr(data-invalid);

... displays the error message.


This only works provided each element has a label. It will not work if you put the attribute on the element itself, because <input> elements cannot have :after pseudo elements.



As mentoned by @Diego you can use form.reportValidity();
To support IE and Safari include this polyfill, it just works:

if (!HTMLFormElement.prototype.reportValidity) {
    HTMLFormElement.prototype.reportValidity = function() {
      if (this.checkValidity()) return true;
      var btn = document.createElement('button');
      return false;
var applicationForm = document.getElementById("applicationForm");    
if (applicationForm.checkValidity()) {
} else {

reportValidity() method will trigger HTML5 validation message.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.