Submit HTML5 Form using Javascript and validate its inputs

后端 未结 3 1665
我在风中等你
我在风中等你 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: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.

提交回复
热议问题