微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在通过Ajax请求提交之前使用jQuery进行表单验证

在尝试使用Ajax请求将表单提交到我的PHP脚本之前,我试图让我的表单进行验证.我查看了stackoverflow并没有找到有用的东西.

我有3个输入和一个提交按钮:

<input type="text" name="full-name" id="full-name" value="" placeholder="Full Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<textarea name="message" id="message" value="" rows="8" placeholder="Message"></textarea>
<input type="submit" id="contact-submit" class="contact-submit" value="Submit">
<div id="messageResponse" class="center" style="display:none;"></div>

$(document).ready(function() {

    function validator(){
        return $('form').validate();
    }

    $('form').on('submit',function(e) {
        e.preventDefault();

        $.ajax({
            dataType: 'html',type: 'post',url: 'mail.PHP',data: $('#contact-form').serialize(),beforeSubmit: validator,success: function(responseData) {
                $('#contact-submit').remove();
                $('#messageResponse').fadeIn(1000);
                $('#messageResponse').html(responseData);
            },error: function(responseData){
                console.log('Ajax request not recieved!');
            }
        });

        // resets fields
        $('input#full-name').val("");
        $('input#email').val("");
        $('textarea#message').val("");
    })
});

我应该使用插件吗?我想要的只是用红色边框颜色验证的名称,电子邮件和消息.这给了我一个很头疼的问题,明天我将与客户会面,以确定网站的最终结果.如果我找不到合适的解决方案,我不会问问题.

我也尝试过使用它:jQuery Form Validator Plugin

解决方法

beforeSubmit是malsup ajaxForm插件一个选项,而不是jQuery ajax.仅当validator()返回true时才执行ajax.

$('form').on('submit',function(e) {
    e.preventDefault();
    if (validator()){
        $.ajax({...});
    }
});

在旁边:

而不是使用多行请求jQuery多次选择相同的东西,你可以使用链.

$('#messageResponse').fadeIn(1000).html(responseData);

同样,对于几个元素做同样的事情

$('#full-name,#email,#message').val("");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐