I have a form with a text field populated by datepicker() that I am trying to validate programmaticaly in the click event handler for a button:
var formValid = true;
console.log( Date.now() + ' initial value: ' + formValid );
$('#expiryDate').validate(function(valid,elem){
if(!valid){ formValid = false; }
console.log( Date.now() + ' in expiryDate validate: ' + formValid );
});
console.log( Date.now() + ' after expiryDate validate: ' + formValid );
$('#documentName').validate(function(valid,elem){
if(!valid){ formValid = false; }
console.log( Date.now() + ' in documentName validate: ' + formValid );
});
console.log( Date.now() + ' after documentName validate: ' + formValid );
if(!formValid){
console.log( Date.now() + ' no post...' );
$('.btn').prop('disabled' ,false );
return;
}
console.log( Date.now() + ' would post now...' );
//$.post();
The validation for documentName returns correctly and synchronously. However, the validation for expiryDate does not: formValid is still true when it evaluates it to decide whether to return or to do the $.post().
If I add console.log() outputs, I am seeing that the validator for the expiryDate field is returning well after the code would have already executed the $.post().
As a result, the data is submitted via $.post() even though the validation is failed.
What am I missing?
Here are the console.log() results (the numbers are a tick count for checking timing; true/false refers to the value of formValid):
1526495506879 initial value: true
1526495506881 after expiryDate validate: true
1526495506882 in documentName validate: true
1526495506883 after documentName validate: true
1526495506883 would post now...
1526495507084 in expiryDate validate: false
1526495507086 in expiryDate validate: false
What happens if you nest one validation inside the callback of the other, then the post request inside the inner validation callback, like so: