简体   繁体   English

提交ajax表单之前如何验证?

[英]ajax form validation before submit how?

I am doing ajax cross domain request to my php page on server. 我正在对服务器上的php页面进行ajax跨域请求。 I am posting form from html via ajax to my php page on server. 我通过ajax从html发布表单到服务器上的php页面。 Have problem with validation in client side. 在客户端进行验证时遇到问题。

I don't know how to do validation in client side before send form. 我不知道在发送表单之前如何在客户端进行验证。

html form is standard form, posting input fields: name, last name, message.... My html form, client side: html表单是标准表单,张贴输入字段:名称,姓氏,消息...。我的html表单,客户端:

<script type="text/javascript">

    var output = $('.nesa');

     $(document).ready(function(){
     $("#form1").submit(function (e) {
     e.preventDefault();

    $.ajax({
        url: 'http://www.example.com/form.php',
        crossDomain: true, //set as a cross domain requests
        type: 'post',
        data: $("#form1").serialize(),
        beforeSend: function (){
        // add spinner
         $('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
                   },

        success: function (data) {
            $(".nesa").html(data);
            alert("sent " + data);

        },

        error: function(){

            output.text('Message is not sent!');

        }

    });
});

});

How to to validation? 如何验证? I try to put code in beforeSend but without success. 我尝试将代码放入beforeSend中,但没有成功。 Or maybe to use submitHandler? 或者也许使用submitHandler?

Idea is when user click submit, that validation start, and if fails to tell "insert your email address". 想法是用户单击提交时,验证开始,如果没有告诉“插入您的电子邮件地址”。 Now when i click submit it send data to server. 现在,当我单击提交时,它将数据发送到服务器。 I want that first check input fields. 我要先检查输入字段。

This form is actual working it sending data to server, but just need to figure out how to do validation. 这种形式在将数据发送到服务器时是可行的,但只需要弄清楚如何进行验证即可。 Where to put validation in ajax call? 在ajax调用中将验证放在哪里?

Thanks 谢谢

Create a function to validate form which return true/false. 创建一个函数来验证返回true / false的表单。 Call the function just before the $.ajax. 在$ .ajax之前调用该函数。 check if return is false then return.. see the example below... 检查return是否为false,然后返回..参见下面的示例...

if(!validateForm())
    return false;

Please validate the form before sending ajax request. 发送ajax请求之前,请验证表单。 If there is no error then ajax request should be send otherwise return false. 如果没有错误,则应该发送ajax请求,否则返回false。 You can do like: 您可以像这样:

 $("#form1").submit(function (e) {
     e.preventDefault();

    // Get the Login Name value and trim it
    var name = $.trim($('#name').val());

    // Check if empty of not
    if (name === '') {
        alert('Text-field is empty.');
        return false;
    }
});

You can see the demo Here's ( http://jsfiddle.net/LHZXw/1/ ) 您可以在此处查看演示( http://jsfiddle.net/LHZXw/1/

You can also make a function onKeyup. 您还可以使onKeyup函数。

First, are you actually using an AJAX form? 首先,您实际上是在使用AJAX表单吗?

You explained that you load the form itself via AJAX, but do you send it that way, too? 您解释说您是通过AJAX加载表单本身的,但是您也以这种方式发送吗? It looks to me that you're trying to send it the HTML way. 在我看来,您正在尝试以HTML方式发送它。 You can hook into the click event of the send button before you send the form. 您可以在发送表单之前加入发送按钮的click事件 However, since the button is added to the page at runtime, you need to register the event to document . 但是,由于按钮是在运行时添加到页面的,因此您需要将事件注册到document

$(document).on('click', 'input[type=submit]', function() {
    // Validate form
    // Add error message on fail, and return
    // Else submit form via AJAX
});

In either case, you can use jQuery's blur event as an alternative to validate each field when the user jumps to the next. 无论哪种情况,当用户跳转到下一个字段时,都可以使用jQuery的blur事件作为验证每个字段的替代方法。 You could even validate every time the user presses a key with keypress . 您甚至可以在用户每次使用keypress

I always validate them right before I enter them into an AJAX call. 在将它们输入AJAX调用之前,我总是会立即对其进行验证。 Here is my exampel 这是我的求婚

$('#form_nieuwsbrief').bind('submit',function(){
    var name = $('input[name=naamNieuwsbrief]').val();
    var email = $('input[name=emailNieuwsbrief]').val();

    var proceed = true;
    if (name==""){
        $('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
        proceed = false;
        }
    if (email==""){
        $('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
        proceed = false;
        }
    if(proceed == false){
        $("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");    
        setTimeout(function(){
            $('.alert').fadeOut(400, function(){
                $(this).remove();
                })
            ;},10000
        );
    }

    if(proceed == true){ // make the ajax call

This is just a quick one for a newsletter that just requests name and email. 对于仅要求名称和电子邮件的新闻通讯,这只是一种快速的方式。 But the principle is the same. 但是原理是一样的。 Just before you make an ajax call, create the if else statement with a variable you set if something is false. 在进行ajax调用之前,请使用您设置的变量(如果出现错误)创建if else语句。 else you stick it tot he original validation, thus you can proceed. 否则您将其保留在原始验证上,因此可以继续进行。

You're already validating via server side correct? 您已经通过服务器端验证了吗? Why don't you use that same validation rules to appear like your client side - via Ajax. 您为什么不通过Ajax使用相同的验证规则来使外观像客户端一样。 I have a tutorial on how to do that: 我有一个有关如何执行此操作的教程:

http://michaelsoriano.com/how-to-ajax-validate-forms/ http://michaelsoriano.com/how-to-ajax-validate-forms/

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

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