自定义远程验证器错误消息

问题描述 投票:0回答:3

使用自定义远程验证器,您应该如何消除错误消息?

在字段上使用 data-parsley-remote-validator='mycustom' 将会在控制台“未定义的异步验证器”中给出错误,除非验证器已添加到 DOM 就绪状态,即不在另一个函数中。但是,如果它是在 DOM 准备就绪时添加的,那么欧芹会自动调用它,这应该在提交/更改或您设置的任何其他内容之前不会发生。

我可以做这样的事情,但这有点违背了让欧芹在变化时调用验证器的目的:

$('#signUpForm').on('submit', function() {
//add the attribute here to avoid the initial error message
  $('#exampleInputEmail1').attr('data-parsley-remote-validator', 'validateEmail');
//then add the custom validator
  $('#exampleInputEmail1').parsley()
  .addAsyncValidator('validateEmail', function (xhr) {
           if(xhr.status == '200') {
               return 200;
             }
          // return the error message if email is taken
           else if(xhr.status == '404') {
             response = '<ul class="errorlist"><li>That email has already been taken, please try another</li></ul>'
             $('#errorResponse').html(response);
            }
      }, '/api/v1/email/available', { "type": "POST", "dataType": "json", "data": data }
   );
 });
parsley.js
3个回答
2
投票

对于那些来到这里查看 Parsley.js 中自定义远程验证器错误消息的人,

您可以将

data-parsley-remote-message
添加到元素,

<input type="text"  data-parsley-remote-validator="my_remote_validator" data-parsley-remote-message="Custom error message only for remote validation on this element" >

使用 Parsley.js 进行测试 - 版本 2.3.11


1
投票

您的异步验证器本身不应该设置错误消息,它应该简单地返回值是否验证。错误消息使用不同的 API 添加和/或指定为数据属性,请检查文档。


0
投票

您可以通过传递给验证器的函数使用 AsyncValidator 添加自定义验证消息

function (xhr) {

// if validations are good, return true or a resolved promise
  if (xhr.status == 200)
    return true;

// Return a rejected promise with the error message you want to display
return Promise.reject("Custom Validation Error")

}

通过这种方式,您可以为每个验证器和/或根据请求的结果设置自定义错误消息

使用 Parsley.js - 版本 2.9.2 进行测试

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