Using Foundation 6 Abide, I've created a custom validator that needs to check a username field against a pattern AND also have it reach out to the server to see if the username is already registered. When the custom validator is executed, it first tests the username against a regex pattern - if that succeeds, it then executes an ajax call to the server to see if the username exists. Since javascript doesn't wait, the custom validator function returns "true" indicating everything is OK. When the ajax call completes, if the username was found, it calls the "addErrorClasses" on the field. This works perfectly, however I'm concerned that since the validator previously returned "true" since it didn't want to wait on the ajax, that now there's no way to return "false" and the form will think it is in a valid state.
QUESTION: Does calling the addErrorClasses function mark the field as invalid, which would then make the form in an invalid state?
Foundation.Abide.defaults.validators.validate_username =
function($el,required,parent) {
// parameter 1 is jQuery selector
if (!required) return true;
let val = $el.val();
// Step 1 - check that it meets the pattern
if (!val.length)
return true;
let valid = new RegExp(username_pattern).test(val);
if (!valid)
return false;
// Step 2 - check that the username is available
$.ajax({
url: "http://localhost:3000/users/"+val,
}).done(function(data) {
$('#demo-form').foundation('addErrorClasses',$el);
console.log(data);
}).fail(function() {
// do nothing for now
});
return true;
};
Yes by calling the addErrorClasses will mark that control as 'invalid' but it depends where and how you call the method.
Since you are executing the ajax(i.e. asynchronous) it returns true by default. By that time your control will be 'valid' and when the ajax receives the response from the 'url' it sets 'invalid' based on your code.
When you try to submit the form the foundation framework resets all the control i.e. it removes all the 'data-invalid' attribute and then executes all the default and custom validators. Still your method return true. It doesn't wait for the response from your ajax.
The form will be submitted even if you have errors in your control.