Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to manually show a HTML5 validation message from a JavaScript function.

In this article, we’ll look at how to manually show a HTML5 validation message from a JavaScript function.

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

To manually show a HTML5 validation message from a JavaScript function, we can call the reportValidity method.

For instance, we write:

<form>
  <input type="email" id="email" placeholder="email" required>
  <button type="submit">Submit</button>
</form>

to add a form.

Then we write:

const form = document.querySelector("form");
if (form.checkValidity()) {
  form.submit();
} else {
  form.reportValidity();
}

We select the form with document.querySelector.

Then we call checkValidity to validate the form values.

Then we call reportValidity when there are invalid form values.

As a result, we should see form validation messages.

Conclusion

To manually show a HTML5 validation message from a JavaScript function, we can call the reportValidity method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *