Parsley.js isValid()使用自定义验证器返回null

问题描述 投票:1回答:1

我正在使用parsley.js(2.8.1)自定义验证器来检查服务器上是否已存在输入代码。一切正常,但parsley().isValid()parsley().validate()提交时返回null

删除自定义验证器工作正常,但我无法从客户端检查服务器上的现有代码。

     <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>

我想检查并提交表格并做ajax的事情。

jquery ajax forms validation parsley.js
1个回答
0
投票

选项1:

因为您的代码适用于promises,请从whenValidate移至documentation

返回boolean或null的validate({group,force})方法将始终返回null,因为远程验证始终返回open promises。

请注意,如果为true,则处理程序缺少return语句。

请阅读parsley.remote.js的内部实现以供参考(如果仍然复杂,请转到option2)

选项2:

你可以将parsley.remote.js js文件添加到你的项目中,然后使用addAsyncValidator

远程使用herehere的好例子。

© www.soinside.com 2019 - 2024. All rights reserved.