jQuery验证:表单被验证两次

时间:2016-06-16 12:42:03

标签: javascript jquery jquery-validate

我有一个表单,我使用jQuery Validate来验证表单。我遇到了一个问题。该表单正在验证两次。

后,我的变量'isValid'被记录到控制台两次

触发验证的按钮是一个类型按钮

<button type="button" name="submit" id="submit" vclass="btn btn-default">Submit</button>

以下是具有要向用户显示的规则和消息的JavaScript。它还包括按钮的点击事件。

$(function () {
$("#createUser").validate({
    rules: {
        FirstName: "required",
        email: {
            required: true,
            minlength : 2
        },
        zipCode: {
            required: true,
            maxlength : 5
        },
        Telephone: {
            required: function (element) {
                return $('#options option:selected').val() != "1";
            },
            maxlength : 12
        },
        options: {
        required: true,
        notEqual: "1"
        }
    },
    messages: {
        FirstName: "Please specify your first name",
        email: {
            required: "This email field is required.",
            minlength : "email had to have a min length of 2."
        },
        zipCode: {
            required: "Zip code is a required field.",
            maxlength : "zip code cannot be more than 5 characters."
        },
        Telephone: {
            required : "Telephone is a required field.",
            maxlength : "Phone number has to have a max length of 12 characters."
        },
        options: {
            required: "Option is a required field",
            notEqual: "Select a different option"
        }
    }
  });

jQuery.validator.addMethod("notEqual", function (value, element, param) {
    return this.optional(element) || value != param;
}, "Please specify a different (non-default) value");


  $('#submit').on('click', function () {
     isValid = $('#createUser').valid();
     console.log(isValid);
  });
});

我发现的大多数问题都与表单被验证两次有关,而不是类型提交而是按钮。另外,我没有在我的JavaScript文件中的任何地方调用提交。我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

如果规则在单独的js中,请确保脚本未被引用两次,