仅使用提交按钮激活验证

时间:2014-02-12 22:03:40

标签: jquery jquery-validate submit

我正在使用按钮进行文件上传。如果我按下它,它就会开始验证。如果我按下提交按钮,我怎么才能激活验证?

Html Formular

<form id="form_import"method="post" enctype="multipart/form-data">  

<button>Choose File</button><span id="filename">no file chosen.</span>
<input type="file" name="file"/>
<input type="submit">

</form>

的Javascript

$(document).ready(function() {
$("button").click(function() {
    $("input[type='file']").click();
})
});

$(document).ready(function() {
$("input[type='file']").change(function() {
    var filename = $("input[type='file']").val().split('\\').pop();
    $("#filename").html(filename);
})
});

$(document).ready(function() {
$("input[type='submit']").click(function() {
    $("[id^=form]").validate({
        submitHandler: function(form) {
            form.submit();
        }
    })
})
});

$(document).ready(function() {
$("#form_import").validate({
    rules: {
        "file": {
            required: true
        }
    }
})
});

CSS

input[type=file] {
visibility: hidden;
}

1 个答案:

答案 0 :(得分:0)

您使用的插件不正确,以及其他一些不寻常的事情。

1)对于每个代码块,您不需要单独的DOM就绪事件处理程序$(document).ready(function(){...})。它们都可以包含在一个实例中。

2)您不能多次致电.validate().validate()方法仅用于 初始化 表单上的插件......没有别的。随后调用它将无效。

3)您不应.validate()置于click处理程序中。由于您已经在DOM就绪处理程序中调用它,因此无论如何都将忽略该第二个实例。

4)您将form.submit()置于submitHandler回调函数内。这完全是多余的,因为它已经是插件的默认行为。如果这是您submitHandler中唯一的代码,那么您可以删除整个submitHandler功能。由于上面的原因#3,它也被忽略了。

5)如果您希望jQuery Validate插件不将<button>视为submit,请使用type="button属性。

<button type="button">Choose File</button>

6)由于隐藏了input type="file"元素,因此必须告诉jQuery Validate插件不要通过其ignore选项忽略隐藏元素。 Setting this option to [] is enough

$("#form_import").validate({
    ignore: [],  // <- don't ignore hidden elements
    rules: {
        "file": {
            required: true
        }
    },
    // all other rules, options, or callback functions
})
相关问题