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
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:
<!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>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">
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.