Rohit
Rohit

Reputation: 89

Parsley Validator with call back not wroking

I am new to javascript world and trying to add new parsley validator , In my validation method I am calling another function with callback result , where I have put my logic to check a URL is image or not .. However validator function is returning before the callback result .. I am stuck with this from last 2 days .. any help will be really appreciated ..below is my code snippet ..

var invalid = false;
window.Parsley
  .addValidator('validUrl', {
    validateString : function(url) {

    checkURLForImage(url , function(result){
              if(result == "error" || result == "timeout" ){
                    console.log('this should print first');
                    invalid = true;
                  }
                  else{
                     invalid = false;
                  }
                 });

       console.log('this should print in last');
       return !invalid;
    },
    messages: {
      en: 'Please upload only valid image url and correct any broken preview images',
    }
  });

Upvotes: 0

Views: 264

Answers (2)

Rohit
Rohit

Reputation: 89

Thanks @Mark for the hint . I am able to do it using promise as below :

window.Parsley.addValidator('validImgUrl', {
    validateString : function(url) {
        return new Promise(
                       function (resolve, reject) {
                        checkURLForImage(url)
                       .then(function (fulfilled) {
                           console.log('fulfilled -- > ' +fulfilled);
                           resolve(true);
                      }).catch(function (error) {
                           console.log('error -- > ' +error);
                           reject(false);
                       });
                    }
                );
    },
    messages: {
      en: 'Please upload only valid image url and correct any broken preview images',
    }
  });

Upvotes: 0

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79612

You don't seem to be returning anything from validateString, so clearly this can't work.

If checkURLForImage works only with a callback, you should return a promise from validateString that you resolve or reject within the callback.

Good luck.

Upvotes: 1

Related Questions