Im trying to validate a phone number against a country code in Backbone.js. I need to wait until after the the ajax callback is executed before returning the result of the validation. I'm using Jquerys when method. The model's validate function is:
validate: function(attrs) {
this.errors = [];
if(attrs['phone'].length>0){
//validate
console.log('before when ');
$.when(this.checkPhoneNumber(attrs)).done(function(response){
console.log('resspone is ');
console.log(response);
if(response.valid!==true){
that.errors.push({input_tag: 'phone', error: 'Please enter a valid phone number'});
}
if(that.errors.length > 0){
return that.errors;
}
});
console.log('after when ');
}
else{
console.log('in the else so no phone number');
if(this.errors.length > 0){
return this.errors;
}
}
},
And checkPhoneNumber is:
checkPhoneNumber: function(attrs){
return $.ajax({
url: "http://hidden-oasis-1864.herokuapp.com/check-phone-number/"+attrs['country']+"/"+attrs['phone'],
success: function(response){
console.log('in checkPhoneNumber success');
},
error: function(){
that.errors.push({input_tag: 'phone', error: 'There was an error validating the phone number'});
return that.errors;
}
});
},
In the view, I do:
if (!this.model.isValid()) {
this.processErrors(this.model.validationError);
}
isValid() runs the model's validate() methos.
But in the logs I always get:
before when ContactModel.js:46
after when ContactModel.js:63
MODEL IS VALID ContactItem.js:66
in checkPhoneNumber success
So when() is not waiting. What am I doing wrong?