jQueryValidate:无法验证字段

时间:2017-01-20 11:56:59

标签: jquery validation

我正在努力验证表单,但只验证了电子邮件地址。这是我的片段:

    $('#toggle-delivery').click( function() {       
      $("#validate-info").validate({         
        rules: {
    email_address: {
            required: true,
            email: true
          }
phone_number: {
required: true,
digits: true,
minlength: 9
}
    shipping_first_name: {
            required: true,
            minlength: 2
          }
    shipping_last_name: {
            required: true,
            minlength: 2
          }
    shipping_address_1: {
            required: true,
            minlength: 10
          }
        }
      }).form(); 
    });

这样可确保仅在单击按钮#toggle-delivery时验证表单。它到目前为止运作良好,但未验证电话号码,运输名字,送货地址和送货地址。例如,对于电话号码,虽然我指定只输入最少9个字符的数字,但如果您在其中键入任何内容(即字母),它会自动将valid类添加到输入元素。对于尚未验证的其他三个字段,即使规则说它应该至少为10,也可以插入1个字符。这就好像规则将被忽略一样。

我还尝试在每个字段中添加自定义错误消息:

jQuery(document).ready(function() {
    jQuery('#validate-info').validate({
onfocusout: function(e) {
            this.element(e);
        },
  messages: {
    email_address: {
      required: "We need your email address to contact you.",
      email: "Oops! This isn't a correct email format. Please check and try again."
    }
}
    });

});

这很有效,但如果我为电话号码添加自定义消息,它就会停止工作。为什么没有验证字段?

1 个答案:

答案 0 :(得分:0)

尝试在您的规则之间添加逗号,如下所示:

    $('#toggle-delivery').click( function() {       
  $("#validate-info").validate({         
    rules: {
email_address: {
        required: true,
        email: true
      },
phone_number: {
required: true,
digits: true,
minlength: 9
},
shipping_first_name: {
        required: true,
        minlength: 2
      },
shipping_last_name: {
        required: true,
        minlength: 2
      },
shipping_address_1: {
        required: true,
        minlength: 10
      }
    }
  }).form(); 
});