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.).
JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/
HTML Form:
<form> <input type="email" id="email" placeholder="Enter your email here..." required> <button type="submit">Submit</button> </form> <button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>
JavaScript:
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.
JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation. It is preferred by most of the web developers. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.
Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted. See the updated fiddle. As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.
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.
var applicationForm = document.getElementById("applicationForm"); if (applicationForm.checkValidity()) { applicationForm.submit(); } else { applicationForm.reportValidity(); }
reportValidity() method will trigger HTML5 validation message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With