3

I am using parsley.js(2.8.1) custom validator to check if input code already exists on server. Everything works fine but parsley().isValid() and parsley().validate() returns null when submit.

Removing custom validator works fine but I am unable to check existed code on the server from client side.

     <form id="product-form">
   [....]
   <input id="product-code"
    data-parsley-code="check-code" data-parsley-length="[3,32]"
    type="text" class="form-control" required>
   [....]
   </form>

   <script>
    $(function(){
        let formInstance = $('#product-form');
        formInstance.parsley();
        Parsley.addValidator('code', {
            validateString: function(value, requirement) {
                let xhr = $.post('/product/' + requirement + '/' + value);
                return xhr.then(function (json) {
                    if (!json.status) {
                        return $.Deferred().reject(json.message)
                    }
                })
            },
            messages: {en: 'Failed to check product code.'}
        });

        formInstance.on('submit', function(e) {
        e.preventDefault();
          console.log(formInstance.parsley().validate());  // returns null
          console.log(formInstance.parsley().isValid()); // returns null
       if (formInstance.parsley().isValid())) {
           [.....]
       }
   }
    [.....]
    </script>

I would like to check and submit form and do the ajax stuff.

Debendra
  • 1,132
  • 11
  • 22

1 Answers1

0

Option1:

Because your code works with promises, move to whenValidate, from documentation:

The validate({group, force}) method that returns a boolean or null will always return null due to remote validation always returning open promises.

Pay attention that your handler is missing a return statement in case of true.

Please read the inside implementation of parsley.remote.js for a reference (if its still to complicate, move to option2)

Option2:

You can add the parsley.remote.js js file into your project and then make use of the addAsyncValidator

Good example of the remote usage here and here.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91