I'm currently working on a form validation that requires a little bit of ajax. With the help of this post, I had each validation fire sequentially.
I now need to break the promise as soon as it sees a false value in the array of validations vs. completing regardless of the true/false values within the array. How could I incorporate this concept based on what I have now?
var validations = [validatePassword, validateName, validateAddress, ...];
$continueButton.on('click', function() {
subscribe().then(function() {
// Do something
}, function() {
// Show error
});
});
function subscribe() {
var promises = validations.map(function(validation) {
return validation();
});
return Promise.all(promises);
}
function validatePassword() {
var password = $password.val();
var format = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])[^+&\n]{8,}$/;
return validateInput(format.test(password), $password);
}
function validateAddress() {
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: '/address/validate',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
var hasValidAddres = response.Data === 200;
validateInput(hasValidAddres, $address);
hasValidAddres ? resolve() : reject();
},
error: function() {
// Show error
}
});
});
}
function validateInput(validation, $input) {
if (validation) {
$input.removeClass('invalid');
return true;
} else {
markAsInvalid($input);
// Was originally return false
return Promise.reject('Example Error');
}
}
function markAsInvalid($input) {
$input.addClass('invalid');
}