简体   繁体   English

来自元素属性的自定义错误消息:jQuery验证插件

[英]Custom error message from element's attribute : jQuery Validate Plugin

We are using jQuery Validate Plugin for all client side validations. 我们正在使用jQuery Validate Plugin进行所有客户端验证。

Until now, we were using default error message for all the required fields (ie 'This field is required'), but now we need to change it to field specific error message. 到目前为止,我们在所有required字段(即“此字段必填”)中都使用了默认错误消息,但是现在我们需要将其更改为特定于字段的错误消息。 For example, if user doesn't enter first name, the message should be displayed as Please enter first name and so on. 例如,如果用户未输入名字,则消息应显示为“ Please enter first name ,依此类推。

These are the possibilities we have tried: 这些是我们尝试过的可能性:

  1. Using HTML 5 attributes data-rule-required="true" and data-msg-required="Madam/sir, this field is required." 使用HTML 5属性data-rule-required="true"data-msg-required="Madam/sir, this field is required." . Due to some other restrictions, we have to avoid using HTML 5 attributes. 由于其他一些限制,我们必须避免使用HTML 5属性。

  2. Providing messages object while validating form: messages: { username: {required: "Please enter Username",email: "Enter valid Email"}, password: "Please enter Password" }, The disadvantage of this method is that we need to modify both html and the javascipt files and the field names must be in sync for proper functining of the plugin. 在验证表单时提供messages对象: messages: { username: {required: "Please enter Username",email: "Enter valid Email"}, password: "Please enter Password" },此方法的缺点是我们需要修改html和javascipt文件都必须同步,并且字段名称必须同步才能正确使用插件。

I am looking for a similar solution to that of HTML 5 attributes - where I can specify a custom attribute to my input fields, the plugin will pick up the message from that field itself. 我正在寻找与HTML 5属性类似的解决方案-我可以在其中为输入字段指定自定义属性,插件将从该字段本身获取消息。 Something like this: 像这样:

<input type="text" required errorMessageCustomAttr="Please enter first name" />

I have referred to relevant SO questions, but unable to find any solution. 我已经提到了相关的SO问题,但是找不到任何解决方案。 Is there any way to achieve this? 有什么办法可以做到这一点?

Quote OP : 引用OP

"I am looking for a similar solution to that of HTML 5 attributes - where I can specify a custom attribute to my input fields, the plugin will pick up the message from that field itself." “我正在寻找一种与HTML 5属性类似的解决方案-在这里我可以为我的输入字段指定一个自定义属性,该插件将从该字段本身接收消息。”

The answer is "no", this is not an option of the plugin. 答案是“否”,这不是插件的选项。

You would use the HTML5 attribute for the custom messages. 您可以将HTML5属性用于自定义消息。 Since HTML5 validation is dynamically disabled by the jQuery Validate plugin, the HTML5 data attribute simply becomes a custom attribute. 由于jQuery Validate插件动态禁用了HTML5验证,因此HTML5数据属性仅变为自定义属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM