提交前的Ajax验证

3
抱歉,可能对于更有经验的用户来说,这是一个基础问题,但我正在学习Ajax,这是一个陡峭的学习曲线,但我慢慢地接近目标。我有以下脚本,它可以完美地工作,除了客户端验证部分。我试图阻止表单在表单字段为空时被提交。然而,我的验证部分没有起作用(被忽略/跳过)。
如果有一位有 Ajax 经验的人能检查一下我的代码并可能提出建议,我将不胜感激。
 <div id="depMsg"></div>
<form name="dep-form" action="deposit/submitReference.php" id="dep-form" method="post">
        <span style="color:red">Submit Reference Nr:</span><br />
         <input type="text" name="reference" value="" /><br />
         <span id="reference-info"></span><br /> 
        <input type="submit" value="Submit" name="deposit" class="buttono" />
        </form>
             </div>

  $(function() {

         var valid
         //call validate function
         valid = validateDep()
         if(valid){
        // Get the form.
        var form = $('#dep-form');

        // Get the messages div.
        var formMessages = $('#depMsg');

        // Set up an event listener for the contact form.
        $(form).submit(function(e) {
            // Stop the browser from submitting the form.
            e.preventDefault();

            // Serialize the form data.
            var formData = $(form).serialize();

            // Submit the form using AJAX.
            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error').addClass('success');

        // Set the message text.
        $(formMessages).html(response); // < html();

        // Clear the form.
        $('').val('')
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success').addClass('error');

        // Set the message text.
        var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
        $(formMessages).html(messageHtml); // < html()
}
    });

        });

    });

function validateDep() {
    var valid = true;   

    if(!$("#reference").val()) {
        $("#reference-info").html("(required)");
        $("#reference").css('background-color','#FFFFDF');
        valid = false;
}
return valid;
    }

    </script>
2个回答

1
你需要在提交事件处理程序中调用验证代码,在你的代码中,你正在dom准备好处理程序中运行验证,然后如果输入字段有内容,那么你将添加事件处理程序。
$(function () {
    var form = $('#dep-form');
    var formMessages = $('#depMsg');

    // Set up an event listener for the contact form.
    $(form).submit(function (e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        //do the validation here
        if (!validateDep()) {
            return;
        }

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        }).done(function (response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error').addClass('success');

            // Set the message text.
            $(formMessages).html(response); // < html();

            // Clear the form.
            $('').val('')
        }).fail(function (data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success').addClass('error');

            // Set the message text.
            var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
            $(formMessages).html(messageHtml); // < html()
        });

    });

    function validateDep() {
        var valid = true;

        if (!$("#reference").val()) {
            $("#reference-info").html("(required)");
            $("#reference").css('background-color', '#FFFFDF');
            valid = false;
        }
        return valid;
    }
})

1
我觉得我的解决方案比其他答案提供的要简单一些。
如果你已经安装了jQuery验证库(例如:jQuery.unobtrusive),那么就很简单了:
$("form").on('submit', function(e) {
    e.preventDefault();
    if ($(this).isValid()) {
        $(this).submit();
    }
}); 

否则,我会将提交按钮变成普通按钮:
<button>Submit</button> instead of <input type='submit' />

然后执行这个操作:
$("button").on("click", function() {
    if ($("form input[type=text]").val() == "") {
        alert("Error!");
    } else {
        $.ajax({
            url: "/my/forms/action",
            type: "POST",
            data: $("form").serialize(),
            success: function() { }
        });
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接