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.