简体   繁体   English

提交前的Ajax验证

[英]Ajax validation before submit

Apologies for opening what might be a basic question for more experienced users but Im learning Ajax it is a steep learning curve but I am slowly getting there. 为更有经验的用户打开可能是一个基本问题的道歉但我正在学习Ajax这是一个陡峭的学习曲线,但我正慢慢地到达那里。 I have the following script which works perfectly, except for the client-side validation part. 除了客户端验证部分之外,我有以下脚本可以正常工作。 Im trying to stop the form from being submitted if form field is empty . 如果表单字段为空,我试图阻止提交表单 However my validation part is not working (it gets ignored / skipped) 但是我的验证部分不起作用(它被忽略/跳过)

I would greatly appreciate it if someone with a bit of Ajax experience could give my code a scan and possibly advise where I am going wrong. 如果有一点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>

You need to call the validation code inside your submit event handler, in your code you are running the validation in the dom ready handler then if the input field has contents then you are adding the event handler. 您需要在提交事件处理程序中调用验证代码,在代码中,您在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;
    }
})

I feel like my solution is a little simpler than the other answer provided. 我觉得我的解决方案比提供的其他答案简单一些。

If you have jQuery validation library installed (ie: jQuery.unobtrusive) it is as simple as: 如果您安装了jQuery验证库(即:jQuery.unobtrusive),它就像下面这样简单:

$("form").on('submit', function(e) {
    e.preventDefault();
    if ($(this).isValid()) {
        $(this).submit();
    }
}); 

Otherwise I would just turn the submit button in to a regular button: 否则我只需将提交按钮转到常规按钮:

<button>Submit</button> instead of <input type='submit' />

And then do this: 然后这样做:

$("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