繁体   English   中英

提交前的Ajax验证

[英]Ajax validation before submit

为更有经验的用户打开可能是一个基本问题的道歉但我正在学习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>

您需要在提交事件处理程序中调用验证代码,在代码中,您在dom ready处理程序中运行验证,然后如果输入字段包含内容,则您要添加事件处理程序。

$(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;
    }
})

我觉得我的解决方案比提供的其他答案简单一些。

如果您安装了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() { }
        });
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM