3

How to execute the native browser form validation using jquery / javascript as if the user is trying to submit the form?

<form id="myform">
    <input type="text" name="myinput" required />
    <input type="email" name="myemail" required />
</form>

<div id="externalcheck">click to validate</div>

<script type="text/javascript">
   $("#externalcheck").click(function(){
     // how to run html5 browser's validation ?
   });
</scrpipt>
Michele
  • 1,468
  • 3
  • 24
  • 54

3 Answers3

3

My example with ajax.

var $form = $('form');

$form.find(':submit').on('click', function (evt) {
    // If the validation fails, return true and the form is processed as standard
    if($form[0].checkValidity() === false) {
      return true;
    }

    evt.preventDefault();

    $.post('/', $form.serialize(), function (response) {
        // Handling the response
    })
})
dakiesse
  • 522
  • 1
  • 6
  • 17
2

See this demo: http://jsfiddle.net/3JeZ6/10/

Here is an HTML for it:

   <style>
      .valid { color: #0d0; }
      .invalid { color: #d00; }
   </style>       
   <form id="testform" action="/">
      <label>Required:
        <input id="required_input" required="">
      </label><br>
      <label>Pattern ([0-9][A-Z]{3}):
        <input id="pattern_input" pattern="[0-9][A-Z]{3}">
      </label><br>
      <label>Min (4):
        <input id="min_input" type="number" min="4">
      </label><br>
        <input type="submit" value="Submit Button" id="sbmt" />
    </form>
    <input type="button" value="Trigger click on submit button" id="test">
    <input type="button" value="Trigger form submit" id="test1">
    <input type="button" value="Run checkValidity" id="test2">

That is crazy, as for me, but simple form.submit() really does not work. But, if you trigger a click on a submit button - everything works fine:

$("#test").click(function(){
  $("#sbmt").click(); // works fine
})
$("#test1").click(function(){
  $("#testform").submit();// does not work 
})
$("#test2").click(function(){
  alert($("#testform")[0].checkValidity() ? "valid": "not valid"); // result looks to be correct, but it does not highlight fields that are not valid
})

I've confirmed following behavior in latest Chrome and FireFox

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
-1

You could iterate over the inputs and check if they're valid.

$("#externalcheck").click(function () {
    $('#myform input').each(function () {
        if (!this.checkValidity()) {
            alert($(this).prop('name') + ' is not valid');
        }

    });
});

http://jsfiddle.net/sWxE9/

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28