0

I have an HTML form which I am validating using JavaScript like below code. All the JavasCript code is in an app.js file.

App.js file

function validateForm () {

    var amount          =   document.forms["salesform"]["amount"];               
    var buyer           =   document.forms["salesform"]["buyer"];    
    var buyerRegex      =   /^[a-zA-Z0-9_ ]*$/;     
    var receipt_id      =   document.forms["salesform"]["receipt_id"];  
    var receiptIdRegex  =   /^[a-zA-Z_ ]*$/;        
    let items           = document.querySelectorAll(".items")
    var itemsRegex      =   /^[a-zA-Z_ ]*$/;
    var buyer_email     =   document.forms["salesform"]["buyer_email"];  
    var note            =   document.forms["salesform"]["note"];  
    var city            =   document.forms["salesform"]["city"];  
    var cityRegex       =   /^[a-zA-Z_ ]*$/;
    var phone           =   document.forms["salesform"]["phone"];
    var phoneRegex      =   /^[0-9]*$/;
    var entry_by        =   document.forms["salesform"]["entry_by"];
    var entryByRegex    =   /^[0-9]*$/;

    function validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

    if (amount.value == "") { 
        alert("Please enter the amount."); 
        amount.focus(); 
        return false; 
    } else if (isNaN(amount.value)) {
        alert("Amount must be only numeric value."); 
        amount.focus(); 
        return false; 
    } else if (amount.length > 10 ) {
        alert("Amount must be less than 10 characters long."); 
        amount.focus(); 
        return false; 
    }

    // more validation.....

    return true;
}

In this file I have another jQuery Ajax code validate the form using Server. So that I have added following Ajax code blow that JS validation code:

$("#salesForm").submit(function(e) {
    e.preventDefault();
    $.ajax({
        url : '../process/add-data.php',
        type: 'POST',
        dataType: "html",
        data : $(this).serialize(),     
        beforeSend : function () {
            $(".formResult").html("Please wait...");
        }, 
        success : function ( data ) {
            $(".formResult").html( data );
        }
    });
}); 

for the HTML form

<form name="salesform" id="salesForm" onsubmit="return validateForm();" method="POST">

Now when the form is validating using JavaScript then it also vaidating the form using Ajax.

But first its should validate using JavaScript and then Ajax.

2 Answers 2

1

Remove onSubmit from the element and modify your Ajax function to return invalid form BEFORE making the call.

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

    if(!validateForm()) return;

    $.ajax({
        url : '../process/add-data.php',
        type: 'POST',
        dataType: "html",
        data : $(this).serialize(),     
        beforeSend : function () {
            $(".formResult").html("Please wait...");
        }, 
        success : function ( data ) {
            $(".formResult").html( data );
        }
    });
}); 
Sign up to request clarification or add additional context in comments.

6 Comments

let me do this now.
Remember to have one handler for events (in your case form submit), so that the code will be easier to maintain and you have easy control over what is called first, second etc. Meaning put all the functions you need to call in one submit function as I did above. Also mark the question answered if you have no further questions.
I have another question: After validating the form using JS it's calling Ajax to validate using PHP. But in the PHP page, I have some time limitation that user can't submit within 24 hours. So if it shows the message after validating the form using js then the user will be angry. Is there any way to show that message earlier?
I don't really understand the question. JS validation means validateForm()? And it shows a message that user is not allowed to post, but the message should be displayed before trying to submit or on page load?
All is okay now :) The form is first validate using JS and then jQuery/Ajax with PHP. That's good. From the ajax success user will get an error message if he try to submit the form within 24 hours. Now, I want to call this before the JS validaion FOR only that purpose not to validate the form using Ajax.
|
1

You need to return false inside beforeSend callback, as it is described in official jQuery documentation:

beforeSend Type: Function( jqXHR jqXHR, PlainObject settings )

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

So, you need to do something like this:

beforeSend : function () {
    $(".formResult").html("Please wait...");
    if(!validateForm()) {
        // Here you remove your "Please wait..." message
        return false;
    }
    // Or simply return the value from validateForm():
    // return validateForm();
},

And, of course, remove the onsubmit="return validateForm();" from your form tag.

4 Comments

then It's checking the validation twice. I mean showing me alert message twice for each field
is there any other way?
Sorry, my mistake. I forgot to mention you need to remove the onsubmit from you form tag. This is the best way to do it because you can do whatever you want on beforeSend callback, leaving all the funtionality over your ajax request. But, anyway, glad to know you could solve it.
I've edited my answer, so that it can be useful to someone else in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.