Jquery验证删除规则不起作用

时间:2015-05-20 21:49:17

标签: javascript jquery validation jquery-validate

我根据输入动态设置验证。在添加验证之前,我将删除规则并添加元素是必需的。设置规则后,消息不会消失。

     for (var i = 0; i < data.length; i++) {
        switch (data[i]["FieldName"]) {
            case "ADDRESS_1":             
                $('[name="HomeAddress1Text"]').rules("remove");               
                if (data[i]["Required"] == true) {
                    $('[name="HomeAddress1Label"]').addClass("required");
                    $('[name="HomeAddress1Text"]').rules("add", {
                        required: true,
                        messages: {
                            required: "Required"
                        }
                    });
                } else {
                    $('[name="HomeAddress1Label"]').removeClass("required");
                }
                break;
 case "ADDRESS_2":
                 $('[name="HomeAddress2Text"]').rules("remove");              
                if (data[i]["Required"] == true) {
                    $('[name="HomeAddress2Label"]').addClass("required");
                    $('[name="HomeAddress2Text"]').rules("add", {
                        required: true,
                        messages: {
                            required: "Required"
                        }
                    });
                } else {
                    $('[name="HomeAddress2Label"]').removeClass("required"); 
                }
                break;
           }
      }

enter image description here

上图第1页我选择了Gayana国家/地区Address line2是必填项,并收到错误消息。这是正确的,然后我已更改为USA,我已删除Address Line2的规则但仍显示消息。如何在更改我的下拉列表后删除所有邮件并查看何时再次提交?

2 个答案:

答案 0 :(得分:2)

不要删除required类,而是使用$.rules('remove',...)函数:

$('[name="HomeAddress1Label"]').rules('remove',{
    required:true
});

您可能需要在此更改后重新验证 -

$('form').valid();

答案 1 :(得分:0)

看上去很脏,但是下面的解决方案对我有用。

$("#Name").rules("remove", "required"); //Only this line did not worked in my case
$("#Name").removeClass("input-validation-error");
$("#Name").next().removeClass("field-validation-error");
$("#Name").next().addClass("field-validation-valid");
$("#Name").next().children().text("");