使用parsley.js为每个字段提供多个自定义错误消息支持

我试图使用parsley.jsvalidation一个简单的表单,我在parsley.js上非常初学。我想在一个自定义validation方法中使用window.ParsleyValidator.addValidator()方法显示多个错误消息。所以我试过了以我的方式。

我创建的简单html表单

 Custom Validation Parsley      
Please provide your name, email address (won't be published) and a comment

$("#commentForm").parsley();

以及包含自定义validation方法的javascript文件

 var errorMsg = ""; window.ParsleyValidator.addValidator('checkEmail', function(value) { console.log(value); if (value == "") { errorMsg = "this field must not be empty"; return false; } else { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!regex.test(value)) { errorMsg = "this field must be email ***"; } return regex.test(value); window.ParsleyValidator.addMessage('en', 'checkEmail', errorMsg); } }, 32) //.addMessage('en','checkEmail',window.ParsleyValidator.catalog) ; 

但这对我不起作用。任何人都可以就此提出建议以及如何处理这项任务?

您只能在给定语言环境中为每个约束分配一条消息。

来自http://parsleyjs.org/doc/annotated-source/validator.html :

 addMessage: function (locale, name, message) { if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {}; this.catalog[locale][name.toLowerCase()] = message; return this; }, 

因此,如果您需要多条消息,请定义多个validation器。

也,

更新:

来自http://parsleyjs.org/doc/index.html#psly-ui-for-javascript :

window.ParsleyUI.updateError(parsleyInstance, name, message);
手动编辑错误消息。

此外,您可以通过直接将其分配给catalog而不是使用addMessage()来设置validation程序函数中的消息(请注意,validation程序的名称应全部为小写):

 window.ParsleyValidator.addValidator('checkEmail', function(value) { if (...) window.ParsleyValidator.catalog.en.checkemail = 'Some error message AAA'; else window.ParsleyValidator.catalog.en.checkemail = 'Some error message BBB'; return (...); }, 32);