Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.).

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.

like image 830
Ahmad Avatar asked Jul 09 '13 14:07

Ahmad


People also ask

How do I display HTML5 validation error?

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.

Can JavaScript be used for validation?

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.

How do I create a custom validation in HTML?

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.


2 Answers

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.

like image 145
Diego Avatar answered Sep 17 '22 08:09

Diego


var applicationForm = document.getElementById("applicationForm");     if (applicationForm.checkValidity()) {   applicationForm.submit(); } else {   applicationForm.reportValidity(); } 

reportValidity() method will trigger HTML5 validation message.

like image 45
Lalnuntluanga Chhakchhuak Avatar answered Sep 19 '22 08:09

Lalnuntluanga Chhakchhuak