简体   繁体   中英

ajax form validation before submit how?

I am doing ajax cross domain request to my php page on server. I am posting form from html via ajax to my php page on server. 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:

<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. Or maybe to use 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?

Thanks

Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...

if(!validateForm())
    return false;

Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return 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/ )

You can also make a function onKeyup.

First, are you actually using an AJAX form?

You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click event of the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to 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. You could even validate every time the user presses a key with keypress .

I always validate them right before I enter them into an AJAX call. 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. 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. I have a tutorial on how to do that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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