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

我正在使用 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 操作。

最佳答案

选项 1:

因为您的代码使用 promise,从 documentation 移动到 whenValidate :

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

请注意您的处理程序在为真时缺少返回语句。

请阅读parsley.remote.js的内部实现供引用(如果仍然复杂,请移至选项 2)

选项2:

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

远程使用的好例子here和 here .

https://stackoverflow.com/questions/54377693/

相关文章:

architecture - 已发布并等待对 RabbitMQ/EasyNetQ 主题的回应 - 如

python - virtualenv 没有匹配的分布

javascript - PokeAPI : get complex evolution chain

c# - 继续获取 "Unable to load DLL ' SQLite.Interop.dll

java - MockMvcRequestBuilders.asyncDispatch 提供一个空的

maven - 如何重定向 maven surefire 插件 stdout*deferred 临时

nginx - 使用 apollo 客户端从 nextjs 中的 getInitialProps 方

laravel - 在 Scout 中使用更复杂的 where 子句

phpunit - CakePHP 2 代码覆盖率现在显示为 "No files to genera

angular6 - 我想根据复选框选择显示/隐藏 Angular 6 react 形式组