Submit HTML5 Form using Javascript and validate its inputs

后端 未结 3 1660
我在风中等你
我在风中等你 2020-12-18 20:01

I\'m writing form and adding html5 validation attributes to its input like \"required\", \"autofocus\". I use Javascript to submit the form using document.myForm.submit() bu

相关标签:
3条回答
  • 2020-12-18 20:17

    The pimvdb's answer is based on a workaround to include a hidden submit button.

    HTML5 provides javascript functions to achieve the same thing without a submit button. As Tigraine pointed out, Mozilla documents two validity checking methods for 'form' elements:

    • checkValidity() return true/false and doesn't show anything to the end user
    • reportValidity() return true/false and ALSO shows the validation messages to the end user (like the normal submit button click does)

    <!DOCTYPE html>
    <html>
    <body>
    
    <form name="testform" action="action_page.php">
    E-mail: <input type="email" name="email" required><br/>
    <a href="#" onclick="javascript:console.log(document.testform.reportValidity());return false;">Report validity</a><br/>
    <a href="#" onclick="javascript:console.log(document.testform.checkValidity());return false;">Check validity</a><br/>
    <a href="#" onclick="javascript:if(document.testform.reportValidity()){document.testform.submit();}return false;">Submit</a>
    </form>
    
    </body>
    </html>

    0 讨论(0)
  • 2020-12-18 20:29

    It appears that triggering a click on the submit button does have the correct effect: http://jsfiddle.net/e6Hf7/.

    document.myForm.submitButton.click();
    

    and in case you don't have a submit button, add an invisible one like:

    <input type="submit" style="display:none" name="submitButton">
    
    0 讨论(0)
  • 2020-12-18 20:37

    Why not simply call the validation manually before you do document.myForm.submit()

    What validation framework do you use and what AJAX library?

    In case you use jQuery here is the code to prevent the submit:

    $('#myForm').submit(function(evt) {
      if (! $('#myForm').validate()) {
        evt.preventDefault();
      }
    });
    

    And trigger the submit through:

    $('#myForm').submit();
    

    This would call the validation whenever submit is triggered.. And if the validation fails it prevents the submit from executing. But I'd look at your validationframework as it usually should do this already

    In case you don't use any JavaScript framework you may want to have a look at: element.checkValidity(); and how to invoke the HTML5 validation from JavaScript before even calling submit.

    0 讨论(0)
提交回复
热议问题