www.webdeveloper.com
Results 1 to 2 of 2

Thread: Form validation on submit.

Hybrid View

  1. #1
    Join Date
    Sep 2012
    Location
    Spain
    Posts
    1

    Form validation on submit.

    Hello everybody, I am new at this and I'd like to show you what I coded and what's my problem. I've made a registration form, and I've made some functions to see if the username is taken, if password is right, email, etc...

    But I call those functions on blur and I'd like also to call them on submit.

    I've looked for this on google and I found something that I tried to implement but it doesn't work. Now I'll show you my code.

    Go after code to see description.


    Code:
    $(document).ready(function(){
        
        //Globals
        var usr = $("#username");
        var pass = $("#password");
        var cpass = $("#confirm_password");
        var email = $("#email");
     
        //Username Check
        function validateUsername(){
     
            usr = $("#username").val();
            if(usr.length >= 4)
            {
            $("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');
     
                $.ajax({  
                type: "POST",  
                url: "check.php",  
                data: "username="+ usr,  
                success: function(msg){  
               
               $("#status").ajaxComplete(function(event, request, settings){ 
     
                if(msg == 'OK')
                { 
                    $("#username").removeClass('object_error'); // if necessary
                    $("#username").addClass("object_ok");
                    $(this).html('&nbsp;<img src="tick.ico" align="absmiddle">');
                    return true;
                }  
                else  
                {  
                    $("#username").removeClass('object_ok'); // if necessary
                    $("#username").addClass("object_error");
                    $(this).html(msg);
                    return false;
                }  
               
               });
     
             } 
               
              }); 
     
            }else{
                $("#status").html('<font color="red"><br /><center>The username should have at least <strong>4</strong> characters.</center></font>');
                $("#username").removeClass('object_ok'); // if necessary
                $("#username").addClass("object_error");
                return false;
            }
     
        }
        
        //Password check
        function validatePassword() { 
     
            pass = $("#password").val();
            
            if(pass.length >= 6){
                $("#status2").html('&nbsp;<img src="tick.ico" align="absmiddle">');
                return true;
            }else{
                $("#status2").html('<font color="red"><br /><center>The password should have at least <strong>6</strong> characters.</center></font>');
                $("#password").removeClass('object_ok'); // if necessary
                $("#password").addClass("object_error");
                return false;
            } 
           
        }
        
        //Password confimation check
        function validatePassword2() { 
     
            cpass = $("#confirm_password").val();
            var pass = $("#password").val();
            if(cpass == pass){
                if(cpass.length >= 6){
                    $("#status3").html('&nbsp;<img src="tick.ico" align="absmiddle">');
                    return true;
                }else{
                    $("#status3").html('<font color="red"><br /><center>The password must have at least <strong>6</strong> characters!</center></font>');
                    $("#confirm_password").removeClass('object_ok'); // if necessary
                    $("#confirm_password").addClass("object_error");
                    return false;
                }
            }else{
                $("#status3").html('<font color="red"><br /><center>The passwords<strong> doesn`t match!</center></strong></font>');
                $("#confirm_password").removeClass('object_ok'); // if necessary
                $("#confirm_password").addClass("object_error");
                return false;
            } 
           
        }
        
        function validateEmail() { 
     
            email = $("#email").val();
            var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
            
            if(email.match(mailformat)){
                $("#status4").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');
     
                $.ajax({  
                    type: "POST",  
                    url: "checkmail.php",  
                    data: "email="+ email,  
                    success: function(msg){  
                   
                       $("#status4").ajaxComplete(function(event, request, settings){ 
     
                            if(msg == 'OK')
                            { 
                                $("#email").removeClass('object_error'); // if necessary
                                $("#email").addClass("object_ok");
                                $(this).html('&nbsp;<img src="tick.ico" align="absmiddle">');
                                return true;
                            }  
                            else  
                            {  
                                $("#email").removeClass('object_ok'); // if necessary
                                $("#email").addClass("object_error");
                                $(this).html(msg);
                                return false;
                            }  
                       
                        });
                    }
                });
            }else{
                $("#status4").html('<font color="red"><br /><center>The email <strong>is invalid!</center></strong></font>');
                $("#email").removeClass('object_ok'); // if necessary
                $("#email").addClass("object_error");
                return false;
            } 
           
        }
        
        //Validate checkbox
        function validateCheck() { 
        
            if(document.form.agree.checked == true){
                $("#status7").html('');
                $("#agree").removeClass('object_error'); // if necessary
                $("#agree").addClass("object_ok");
                return true;
            }else{
                $("#status7").html('<font color="red">You must accept the<strong> agreement!</strong></font>');
                $("#agree").removeClass('object_ok'); // if necessary
                $("#agree").addClass("object_error");
                return false;
                
            }
        }
        
        //Validation on blur.
        usr.blur(validateUsername);
        pass.blur(validatePassword);
        cpass.blur(validatePassword2);
        email.blur(validateEmail);
        
        //Validation on submit.  
        $("#signupForm").submit(function(){  
            if(validateUsername() & validatePassword() & validatePassword2() & validateEmail() & validateCheck()){
                return true;
            }
            else{
                return false;
            }
        });
        
    });
    What I've done here (or tried), is making a function for every field of the form, to test if what is written is correct or not. Then I call the events of each one in the event blur after I define all the functions.

    And last one, I try to validate on submit, calling all the functions. But it seems that the functions doesn't return any value. For any reason unknown to me, the functions are made after the the "if sentence", or that's what I think.

    I asked in other forum but someone explained me something I really didn't understand.

    He told me this:
    your code is wrong, your form validates each operation in the server with an AJAX request, who is async and it always return false, except if you use callbacks in chain of onreadystatechange.
    I tried looking for that "onreadystatechange" but I didn't understand any explanation because I am new here.

    Could anyone help me?, thank you in advance.

  2. #2
    Join Date
    Jul 2011
    Posts
    131
    When you submit the form AJAX requests are sent to the server. Let's say that your request is executing 200ms. But your js code will not wait while ajax request will finish. That means that your function that is calling in form submitting will be completed faster than ajax and will always return false.

    When you send ajax request the XmlHttpRequest object is created. It has a property readyState that holds the state of the request. The onreadystatechange property stores a function that will be called when readyState property changes. You can read more about this here onreadystatechange

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles