如何使用 jQuery 验证强制出现单一错误?

发布于 2024-09-07 09:10:23 字数 615 浏览 0 评论 0原文

我在表单上使用 jQuery 验证插件。我通过 javascript 设置基本规则和消息,如下所示:

   rules:{
        "billing.firstname":{
            required:true
        },
    messages:{
        "billing.firstname":"First name is required."}

我有额外的要求,即使用 javascript 函数将字段显示为无效,并带有指定的消息,我使用 validator.addMethod 然后调用 validate().element(element) 来完成此操作在相关领域。

我遇到的问题是我无法使用 addMethod 调用中提供的消息覆盖最初的消息集。因此,当我添加的规则用于验证时,即使我在添加新规则之前清除了所有规则,原始的“需要名字”消息仍然会显示。

有没有办法强制验证单个元素上的单个规则,或者以某种方式访问​​分配的消息,以便我可以暂时更改它?

作为参考,总体目标是页面上发生的一些其他 ajax 类型函数超出了我的控制范围,我需要允许它们使用 JS 函数来手动设置字段无效状态和消息。

提前致谢 -

b

I am using the jQuery validation plugin on my form. I set the basic rules and messages via javascript like this:

   rules:{
        "billing.firstname":{
            required:true
        },
    messages:{
        "billing.firstname":"First name is required."}

I have the additional requirement to use a javascript function to show a field as invalid with a specified message which I am accomplishing using validator.addMethod then calling validate().element(element) on the field in question.

The problem I am having is that I am unable to override the message set initially with the one provided in the addMethod call. So while my added rule is being used to validate, the original 'First name is required' message always displays even if I clear all rules prior to adding the new one.

Is there a way to force validation of a single rule on a single element or alternatively somehow access the message assigned so I can change it temporarily?

For reference the overall goal is there are some other ajax type functions that happen on the page out of my control and I need to allow them to use a JS function to manually set a field invalid state and message.

Thanks in advance -

b

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久光 2024-09-14 09:10:23

仅供参考 - 我想出了如何做到这一点。它是通过插件未记录的方法实现的,但这是我能找到访问初始设置消息的唯一方法。

我目前正在用于

form.validate().settings.messages[elementId]

获取最初设置的特定元素的消息,并将其设置为不同的内容,同时将原始元素保留为元素本身的 .data 部分。这样 onChange 我可以删除自定义消息并重置为原始消息。

FYI - I figured out how to do this. It is via a method that is not documented for the plugin, but was the only way I could find to access the initially set messages.

I'm currently using

form.validate().settings.messages[elementId]

to get the message for a specific element as initially set and setting it to something different while maintaining the original as a .data part of the element itself. This way onChange I can remove the custom message and reset to the original.

b

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文