Manually trigger html5 validation on button click

Imran Rashid picture Imran Rashid · Sep 5, 2013 · Viewed 25.8k times · Source

I am trying to handle form validation on button click. It is validating the form but not showing error. can anyone help me in 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/

Answer

Brian Davis picture Brian Davis · Jul 19, 2017

Try

reportValidity()

So you'd have

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