【问题标题】:How do I show a jQuery validation error on a textbox based on a hidden input field?如何在基于隐藏输入字段的文本框上显示 jQuery 验证错误?
【发布时间】:2011-11-04 04:41:36
【问题描述】:

我有一个下拉列表,我将其转换为自定义模式对话框。转换要求我们有一个显示所选项目名称的文本字段和一个包含所选项目 ID 的隐藏字段:

<input id="template" type="text" class="text inactive" value="Select a template...">
<span class="button">Select...</span>

<input id="templateid" type="hidden" class="required" name="template" title="You must select a template.">

当用户点击 Select... 按钮时,会弹出一个模式对话框,允许用户选择模板。用户选择模板后,template文本框设置模板名称,templateid隐藏字段设置模板ID:

$('#templateDialog .okButton').click(function() {
    var item = $(this).find('li.selected');
    var name = item.find('.name').text();
    var id = item.find('.id').text();
    
    $('#template').val(name);
    $('#templateid').val(id);
    $('#templateDialog').dialog('close');
});

这一切都很好。我现在遇到的问题是验证,使用 jQuery Validation。因为隐藏输入有required 类,所以当我尝试在不选择模板的情况下提交表单时,错误消息会正确显示。但是,template 文本框没有样式。我希望它获得invalid 课程。

我的问题是,我该如何配置 jQuery,如果 templateid 隐藏字段无效,template 文本框也无效,如果有效,文本盒子也有效吗?

更新:这是一张图片:

看到 确认密码 文本框有红色轮廓,而 模板 文本框没有?我也希望它是红色的。

【问题讨论】:

  • 你能贴出 Jquery 验证码吗?
  • 只是$('form').validate();。我正在使用 jQuery 元数据来处理规则。

标签: jquery jquery-validate


【解决方案1】:

jQuery 验证插件提供了两个处理程序来自定义错误字段的视觉更改方式:highlightunhighlight

$(".selector").validate({
    highlight: function(element, errorClass, validClass) {

        if ([case of the input]) {
        // check here the case of you file input and add the errorClass to the file input or its container
        }
        else {
         // don't forget to apply the class to element in the other cases as defining this handler will remove the default behavior
            $(element).removeClass(validClass).addClass(errorClass);
        }
     }
});

使用 unhighlight 处理程序做相反的事情。

希望这会有所帮助, d.

【讨论】:

    【解决方案2】:

    您可以在无效事件上调用函数。

    $(".selector").validate({
       invalidHandler: function(form) {
        // do other stuff for a invalidvalid form
    
       }
    })
    

    this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多