async email validation & promises
See original GitHub issueHi logaretm,
I am making a new custom rule to validate whether an email is already in the system or not, and it is having some issues. I am either miss understanding how to create a custom rule, or the js promise concept.
I hereby include some code. I have basically tried a bunch of different things and the ajax call returns the right values, however, I get the following error. Uncaught TypeError: Cannot read property ‘then’ of undefined(…)
I have the ajax call within an if(value), in case there should be no email i the email field, so that one can return false and not let the validation proceed.
I’ve also poked around with js Promise but that didn’t get anywhere either…
Validator.extend('email_exists', {
getMessage: field => `The email is already in the system.`,
validate: value => {
if(value) {
console.log('email_exists value',value);
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
var request = $.ajax({
type: 'GET',
dataType: "json",
url: 'api/users/email/'+value
});
request.done(function(response) {
// email not in system, return true so registration can proceed
if(response.data.email == '' && response.data.message) {
console.log('email not in system, return TRUE', response);
return true;
}
// email in system, return false so the user can login or register with another email
else {
console.log('email in system, return FALSE', response);
return false;
}
});
request.fail(function(jqXHR, textStatus) {
console.log('email_exists ERROR', textStatus);
return false;
});
} else {
console.log('NO VALUE return FALSE');
return false;
}
}
});
I also tried the following, and I got the same error. Uncaught TypeError: Cannot read property ‘then’ of undefined(…)
created: function() {
this.$validator.extend('email_exists', {
getMessage: field => `The email is already in the system.`,
validate: value => {
console.log('email_exists value',value);
this.$http.get('api/users/email/'+value).then( function(response) {
console.log('then: ', response);
}).catch( function(error) {
console.error('email_exists', error);
});
}
});
....
Any help, example, or guidance is greatly appreciated.😃
All best, Max
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
Hi,
Thanks again for your help 😃
I got the following to work.
API
Validator
You need to return the promise in your validator function,
but you need to make sure that whatever returns from the promise is an object containing a property called ‘valid’ which is boolean value, something like this:
Take a look at a similar example here