[英]How to customize different error messages for the same field?
I have the following field that uses it's own regular expression to validate: 我有以下使用它自己的正则表达式进行验证的字段:
<input type="text" name="first-name" class="form-control" id="first-name" placeholder="First Name"
data-parsley-trigger="change" required data-parsley-alpha data-parsley-pattern="^[A-Za-z]*$"/>
The field has multiple validation failure states, and I want each of those states to have a different error message. 该字段具有多个验证失败状态,我希望每个状态都具有不同的错误消息。
For example, if the user enters a space, I want the error message to say "No spaces allowed", but if it has a numeric character, I want the error message to say "No numbers allowed". 例如,如果用户输入空格,我希望错误消息说“不允许空格”,但是如果它有数字字符,我希望错误消息说“不允许数字”。
I've tried to figure out how to do this by reading the docs, but I'm still confused on how to achieve this. 我试图通过阅读文档来弄清楚如何做到这一点,但是我仍然对如何实现这一目标感到困惑。
I'm using Parsley 2.0.0-rc4
我正在使用Parsley 2.0.0-rc4
Yeah, this is not something easily doable with Parsley. 是的,这对于欧芹而言并非易事。 Each validator have an unique error message. 每个验证器都有一个唯一的错误消息。
If you want to do so, for UI/UX purposes, you may have two possibilities: 如果要这样做,出于UI / UX的目的,您可能有两种可能:
1) You'll need to define some custom validators of yours, and their related messages. 1)您需要定义自己的一些自定义验证器及其相关消息。
In your example: 在您的示例中:
nospaces
and its message with 66 priority 创建一个验证器nospaces
及其优先级为66的消息 nonumbers
and its message with a 65 priority 创建一个验证器nonumbers
及其优先级为65的消息 pattern
validator (64 priority) and eventually change its message by something like 'only alphanum allowed' 仍然使用您的pattern
验证器(优先级为64),并最终通过“仅允许字母数字”之类的方式更改其消息 Add then these 3 validators to your input, and depending on their respective priority they would be fired in the right order to display the right error message you want as described in your question. 然后将这3个验证器添加到您的输入中,并根据它们各自的优先级将它们按正确的顺序触发,以显示您想要的正确错误消息,如问题中所述。
Pros: easily reusable 优点:易于重用
Cons: some work is needed 缺点:需要做一些工作
2) Keep your pattern validator, and bind a custom function to the parsley:field:error
event for this input, and do your check to display the right error message you want for this field, and not the default one 2)保留您的模式验证器,并将自定义函数绑定到此输入的parsley:field:error
事件,并进行检查以显示所需的正确错误消息,而不是默认字段
Pros: less work maybe, in a single function 优点:单个功能可能工作更少
Cons: not much reusable 缺点:可重用性不高
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.