I have a form which is currently submitting via AJAX, however I'd like to use the inline HTML5 pattern validation and required functionality.
How can I achieve this and still submit via AJAX? I've played with a few other answers on here but I'm using this AJAX on a number of forms and passing data to it in the buttons.
I've moved simple JS inline to make this easier to see the entire form
<form enctype="multipart/form-data" action="/processing.php?page=vmrp" method="post" accept-charset="UTF-8" id="formvmrp">
<input type="checkbox" name="changePIN" onclick="document.getElementById(\'pintext\').style.display = (this.checked) ? \'block\' : \'none\'; document.getElementById(\'nopintext\').style.display = (this.checked) ? \'none\' : \'block\'; " /> Change My PIN
<div id="nopintext" style="display: block;">
<button onclick="submitForm(\'vmrp\',\'uvml\')">Unlock Voicemail</button>
</div>
<div id="pintext" style="display: none;">
<label for="edit-submitted-user-name">New PIN: <span class="form-required" title="This field is required.">*</span></label>
<br>PIN Must be 6 numbers<br>
<input required="required" type="password" placeholder="New 6 Digit PIN" id="edit-submitted-user-name" name="PIN" value="" pattern="[0-9]{6}" maxlength="6" size="75" title="PIN Must Contain 6 numbers!" class="form-text required" /><br>
<button onclick="submitForm(\'vmrp\',\'uvml\')">Change PIN</button>
</div>
<input type="hidden" name="form_id" value="uVMResetPIN" />
<input type="hidden" name="uVMPINURI" value="' . (string)$_SESSION['uVMPINURI'] . '" />
<input type="hidden" name="rmtIP" value="' . $_SERVER['REMOTE_ADDR'] . '" />
<input type="hidden" name="tz" value="' . $_SESSION['uVMtzn'] . '" />
<input type="hidden" name="user" value="' . $_SESSION['inUser'] . '" />
</form>
HTML5 validation only works if your form is ever going to get submitted.If you are going to just serialize the form and send via ajax then html5 validation will never occur.Still you call checkValidity()
form method anytime to know if all required inputs have been filled
BUT ..
newer browsers now have implemented reportValidity() method which you can call anytime to validate as well as show whats wrong ie. it will be just like if user has pressed the submit button.Only problem here is some older browsers don't support. You add a conditional check and use if its available
function submitForm(blah,blah)
{
$yourForm = $('#formvmrp');
if (typeof $yourForm[0].reportValidity === "function") {
if($yourForm.reportValidity()) // will evaluate to TRUE if all ok else FALSE and also show validation messages
{
// do ajax
}
} else {
if($yourForm[0].checkValidity()) // will evaluate to TRUE if all ok else FALSE but won't show validation messages
{
// do ajax
}
else {
alert('please fill all the details');
}
}
}