question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

async email validation & promises

See original GitHub issue

Hi 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:closed
  • Created 7 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

7reactions
max76commented, Oct 27, 2016

Hi,

Thanks again for your help 😃

I got the following to work.

API

        if(!$user) {
            // return TRUE when the user doesn't exists, so that one can proceed
            return response()->json([
                'valid' => true
            ]);
        }

        // return FALSE when the user exists, so that one can't proceed
        return response()->json([
            'error' => false
        ]);

Validator

    validate: value => {
        if(value) {
            return this.$http.get('api/users/email/'+value).then(
                function (response) { // success
                    return Promise.resolve(response.json());
                },
                function (response) { // error
                    return Promise.reject(response.json());
                }
            ).catch(function(error) {
                    error: error;
            });
        } else {
            return false;
        }
    }
6reactions
logaretmcommented, Oct 27, 2016

You need to return the promise in your validator function,

return this.$http.get('api/users/email/'+value);

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:

return this.$http.get('api/users/email/'+value).then(response => {
  return {
    valid: response.data.valid // Your api could return a response containing a 'valid property'
  }
});

Take a look at a similar example here

Read more comments on GitHub >

github_iconTop Results From Across the Web

Async validation to external email provider - Marketing Nation
I would like to know if it's possible to call a promise or an async function inside the onValidate Marketo api method ....
Read more >
validator to return Promise or Observable : Custom async ...
I am trying to implement it using RxJs debounceTime, distinctUntilChanged. In the form control I have two more validations required and pattern.
Read more >
Async Validators | JET Developer Cookbook - Oracle
The async validator's validate method returns a Promise that resolves if validation passes and value is updated or rejects with an Error if...
Read more >
Documentation: DevExtreme - JavaScript Validator Async Rule
Validation rules are checked in the following order: All the synchronous rules are checked in the same order as in the validationRules array....
Read more >
Using Custom Async Validators in Angular Reactive Forms
Ocasionally, we want to validate some input in our fields before submission, which will be validated against an asynchronous source.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found