Parsley Custom Remote Validation with AJAX

I had a problem implementing parsley.remote.js due to AMD in our configuration.

I am trying to implement a special validator that executes an AJAX request and returns true or false based on the response.

The problem is that I get a response from false, regardless of what the AJAX request returns.

Why does this code never work?

window.ParsleyValidator.addValidator('cardcode', function (value) { var valid = false; $.ajax({ url: '/data/checkout/cvvCheck.json', data: { cvv: value }, success: function(response) { if(response.valid === true) { return true; } else { return false; } } }); }, 32); 
 <input type="tel" name="card-code" id="card-code" maxlength="4" required="" data-parsley-required="true" data-parsley-required-message="Please enter the cvv" data-parsley-type="number" data-parsley-type-message="Please enter a valid cvv" data-parsley-cardcode="true" data-parsley-cardcode-message="Please ensure you are entering the correct cvv." data-parsley-id="65"> 
+5
source share
1 answer

The problem is that the AJAX call to your remote validator is asynchronous, which means that your answer comes back too late for Parsley, so it will always take a false result for verification.

While synchronous AJAX calls should be avoided , if you add the async: false option to your AJAX call, the code should work:

 window.ParsleyValidator.addValidator('cardcode', function (value) { var valid = false; $.ajax({ url: '/data/checkout/cvvCheck.json', data: { cvv: value }, async: false, success: function(response) { if(response.valid === true) { return true; } else { return false; } } }); }, 32); 

Here's the asynchronous method I found that worked for me - you need to load parsley.remote.min.js instead of parsley.min.js, then configure your own remote validator using this code:

 window.Parsley.addAsyncValidator('cardcode', function (xhr) { var response = xhr.responseText; if (response.valid === true) { return true; } else { return false; } }, '/data/checkout/cvvCheck.json'); 
+6
source

All Articles