如何基于隐藏的输入字段在文本框上显示jQuery验证错误?

时间:2011-11-04 04:41:37

标签: jquery jquery-validate

我有一个下拉列表,我正在转换为自定义模式对话框。转换要求我们有一个文本字段显示所选项目的名称,以及一个隐藏字段,其中包含所选项目的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.">

当用户点击选择... 按钮时,会弹出一个模态对话框,允许用户选择模板。用户选择完模板后,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验证。因为隐藏的输入具有required类,所以当我尝试提交表单而不选择模板时,错误消息会正确显示。但是,template文本框未设置样式。我希望它能获得invalid课程。

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

更新:这是一张图片:

http://img577.imageshack.us/img577/8121/testckl.jpg

查看确认密码文本框的红色轮廓,但模板文本框不是?我也希望它也是红色的。

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

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

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

   }
})

请参阅this