如何通过jquery验证避免隐藏字段的验证?

时间:2012-08-17 07:24:38

标签: jquery jquery-plugins

我有一个下拉状态,包括必需,选项和大约8个文本字段的隐藏状态。即使字段隐藏,也很少有字段得到验证并抛出错误消息。怎么避免这个?请帮忙。

我的代码是:

            function responseFunction(res) {
    //1:mandatory
    //2:optional
    //3:hidden
    var str = res.split("~");
   for (i in str)
    {
     var field= str[i].split(':');
            switch (field[0]) {
            case "BillingAddressLine1": 
                 switch (field[1]) {                    
                  case "1":$('#ContentSection_lblBillingInfoAddress').prepend('<span>*</span>');
                  $("#<%= txtBillingInfoAddress.ClientID %>").rules("add", {required  : true, messages : {
                  required    : 'Please Enter Address'   }});
                  break;
                  case "3":$('#ContentSection_lblBillingInfoAddress, #ContentSection_txtBillingInfoAddress').hide().parent('p').css("paddingTop", "0px");
                  break;
                 }
            break;
            case "BillingFullName": 
                 switch (field[1]) {
                  case "1":$('#ContentSection_lblBillingInfoAccountHolderName').prepend('<span>*</span>');
                   $("#<%= txtBillingInfoAccountHolderName.ClientID %>").rules("add", {required  : true, messages : {
                  required    : 'Please Enter Account Holder Name'   }});
                  break;
                  case "3":$('#ContentSection_lblBillingInfoAccountHolderName, #ContentSection_txtBillingInfoAccountHolderName').hide().parent('p').css("paddingTop", "0px");
                  break;
                 }
            break;
    }
    }

我的屏幕截图是: https://www.dropbox.com/sh/asmpnuiqqlo40us/S9yHCuNSyl?m#f:errorThrowing.jpg

4 个答案:

答案 0 :(得分:2)

为所有隐藏元素添加一个class属性,并使用ignore属性忽略所有这些元素:

<input type='hidden' class='hiddenClass' />

$('form').validate({
 ignore: '.hiddenClass'
});

答案 1 :(得分:1)

隐藏时删除字段验证

$('#targetId').rules('remove');

在可见时重新添加验证

$('#targetId').rules('add', {
    required: true
});

答案 2 :(得分:1)

只需检查下面的案例陈述

var control = $("#<%= txtBillingInfoAddress.ClientID %>");
if($(control).is(':hidden')){
  // remove validation
}

答案 3 :(得分:1)

隐藏来自javascript方法的验证,例如:

function lalala()
{
  var validator1 = document.getElementById('Validator1ClientID');
  ValidatorEnable(validator1, false); 
}