jQuery验证没有停止回发

时间:2013-07-17 16:03:13

标签: jquery validation http-post event-bubbling

我有一个使用jQuery定义的自定义验证器,它会检查以确保在HTTPPost发生之前完成所需的字段。我的脚本如下:

<script>
$(document).ready(function() {
    $('#ContentProperties').hide();
    $('#FileSubmit').hide();
});

$(function () {
    $("input:file").change(function () {
        var fileName = $(this).val();
        if(fileName != null)
            $('#FileSubmit').show();
            $('#ContentProperties').show();
            alert("File successfully chosen please enter required metadata below");
    });
});

$(document).ready(function () {
    $("#FileSubmit").click(function () {
        var name = document.getElementById("name").value;
        var author = document.getElementById("author").value;
        var description = document.getElementById("description").value;
        var uploadDate = document.getElementById("uploaddate").value;
        var expiryDate = document.getElementById("expirydate").value;
        var contentType = document.getElementById("contenttypeid").value;
        var alertString = "";

        if (name.length == 0) {
            alertString += "NAME: You must enter a name for your content!\n" 
        }

        if (author.length < 6) {
            alertString += "AUTHOR: You must enter at least 6 characters for author!\n"
        }

        if (description.length < 20) {
            alertString += "DESCRIPTION: You must enter a valid description of at least 20 characters !\n"
        }

        if (uploadDate.length < 8 || uploadDate.length > 10) {
            alertString += "UPLOAD DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (expiryDate.length < 8 || expiryDate.length > 10) {
            alertString += "EXPIRY DATE: Date must be entered in format 01/01/2013 or 1/1/2013\n"
        }

        if (alertString.length > 0) {
            alert(alertString)
            event.cancelBubble = true;
            event.returnValue = false;
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
    });
});

当我单击提交按钮并将验证字段留空时,它正确显示错误消息,但无法停止发布。使用jQuery时该怎么做?以前我只使用过javascript而且我能够停止冒泡:

event.cancelBubble = true;
event.returnValue = false;
event.preventDefault();
event.stopPropagation();

2 个答案:

答案 0 :(得分:1)

您尚未定义event

$("#FileSubmit").click(function (event) {

虽然我通常使用e作为惯例:

$("#FileSubmit").click(function (e) {
    e.preventDefault();
});

旁注:我会更改此选项以将处理程序附加到表单提交,而不是单击提交按钮。您可以通过按Enter键提交表单,它会跳过您的点击处理程序。

答案 1 :(得分:1)

你没有在函数调用中引用'event':

$("#FileSubmit").click(function (event) { ....