Manual activation of html5 check at the click of a button

I am trying to handle form validation when a button is clicked. It checks the form, but does not show an error. can anyone help me with this?

<form id="the-form" action="#"> <input type="text" required="required" placeholder="Required text" /> <input type="email" required="required" placeholder="email" /> <button id="btn" type="button">Submit</button> </form> 

JavaScript:

 $("#btn").on("click", function(){ if($("#the-form")[0].checkValidity()) { alert('validated'); } else { //show errors return false; } }); 

http://jsfiddle.net/5ycZz/

+6
source share
5 answers

I achieved this by following these steps:

1) I have a form:

 <form> <textarea required></textarea> <input type="submit" style="display:none;"/> </form> <a>Some other button to trigger event</a> 

2) Now we need to check the correctness of filling out the form:

 //this is <a> click event: if (!$('form')[0].checkValidity()) { $('form').find('input[type="submit"]').click(); return false; } 

This will cause the form to be submitted, but not submit, because there are errors;)

It looks like html5 input errors appear on input [type = "submit"] click :)

Hope will work for you too! :)

+3
source

Try

 reportValidity() 

So you will have

 $("#btn").on("click", function(){ if($("#the-form")[0].checkValidity()) { alert('validated'); } else { $("#the-form")[0].reportValidity(); } }); 
+4
source

here is the perfect answer

 <form id="the-form" action="#"> <input type="text" required="required" placeholder="Required text" /> <input type="email" required="required" placeholder="email" /> <button id="btn" type="submit">Submit</button> 

 $("#btn").on("click", function(){ if($("#the-form")[0].checkValidity()) { alert('validated'); } else { return 0; } 

});

+3
source

Delete the else statement. (Update)

 $("#btn").on("click", function(){ if($("#the-form")[0].checkValidity()) { alert('validated'); //will appear if name and email are of valid formats } }); 
0
source

You should simply add onclick = "return validateForm ()".

 <button id="btn" onclick="return validateForm()" type="button">Submit</button> 
-1
source

Source: https://habr.com/ru/post/953231/


All Articles