JQuery validation – part 1 .

Posted: November 30, 2009 in Jquery

Hi everyone , i intend to start a series of tutorials about JQuery validation covering some important topics like integrating php and its Cdoeigniter , using JQuery validation plugins and Doctrine .

Note that : these tutorials represent my own trials !!

Our tutorial consists of two 3 parts as follows :-

  • HTML code : that contains the form and its input and submit and … fields .
  • PHP script : that validates some $_POST information (typed in the form) and either show errors or just type a message saying “thanks for registering“.
  • JQuery code : that is responsible for two jobs (posting data from the form to the php script and getting the result back to the HTML page again).

We start by writing a simple HTML page that contains a form for registering a new user that consists of :-

  1. Input field of type text for the user name .
  2. Two input fields of type text for the email and the re-email .
  3. Two input fields of type password for the password and re-password .

That will be something like this :-

<form id="sendForm" style = "margin-bottom : 0px">
<label for="username">Username : </label>
<input type="text" id="username"/>
<br>
<label for = "email1">Your email :</label>
<input type = "text" id = "email1" />
<br>
<label for = "email2">re-enter your email :</label>
<input type = "text" id = "email1" />
<br>
<label for = "password1">Your password :</label>
<input type = "text" id = "password1" />
<br>
<label for = "password2">re-enter your password :</label>
<input type = "text" id = "password2" />
<br>
<a id="mysubmit" href="#"> Register</a>
and i used this site to get a rounded-corners div that contained my form :

 

http://www.spiffycorners.com/index.php?sc=spiffy&bg=806F6F&fg=C9ABAB&sz=5px

=> My PHP script that will validate data that will be $_POSTed from the previous HTML form will look like this :-

<?php
// this file is named "rules.php"
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
function isValidEmailAddress($email){
  return preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email);
	}
$errors="<ul>";
$flag = false;
// if it is empty
if(strlen($username)){
// if it is not empty check length
       if(strlen($username)>50){
       $flag = true;
       $errors .= "<li>username must be more than 10 chars and lower than 50</li>";
	}
       if(strlen($username)<10){
  $flag = true;
  $errors .= "<li>username must be more than 10 chars and lower than 50</li>";
	}
      }else{
	$flag = true;
	$errors.="<li>Please fill the username field</li>";
	}
// if password is empty
if(strlen($password1)==0 || strlen($password2)==0){
   $flag = true;
   $errors.="<li>each password field must not left empty</li>";
    }else{
         // if they are not left
         if(!($password1=== $password2)){
            $flag = true;
            $errors.="<li>Both password fields must be identical</li>";
            }
         if(strlen($password1)>50){
            $flag = true;
            $errors.="<li>password's field length must be less than 50 chars</li>";
             }
        }
// checking the email
if(strlen($email1) == 0 | strlen($email2) == 0){
    $flag = true;
    $errors.="<li>email's field length must be between 1 and 49 chars</li>";
}else{
    if(!$email1 === $email2){
    $flag = true;
    $errors.="<li>Both email fields must be identical</li>";
      }
    if(strlen($email1)<10){
       $errors .= "email's field length must be more than 10 chars";
       }
    if(strlen($email1)>50){
       $errors.= "email's field length must be less than 50 chars";
       }
    if(!isValidEmailAddress($email1)){
       $flag = true;
       $errors .="<li>Invalid email address</li>";
       }
     }
  $errors .="</ul>";

if ($flag){
   print($errors);
}else{
   print "thanks for registering !";
     }

?>

In the previous code what did i do ?

  • Assigning the $_POST’s elements to variables like $username = $_POST[‘username’];
  • Defining a function that compares its input email address against a regex patterns and returns a boolean value .
  • Defining a variable that will hold errors ( if any ) $errors which will be an unordered list <ul> containing errors as <li>‘s .
  • Checking the $username if its length is more than zero then we check its length to be between 10 and 50 charecters .
  • If not we just add an <li> to the $errors variable containing a message .
  • The rest is similar and logical !
  • Finally we check if the $flag boolean variable was true then we print the errors if not we print a “thank you” message .
  • Instead of printing a “thank you message” we can post these valid information to a database !!

=> And finally the JQuery code that will transfer data from the form to the PHP script using $_POST

and get the result back from the script to the HTML page that contains the form .

$("document").ready(function(){
  $("#mysubmit").click(function(){
    $.post("rules.php",
                 {
                   username : $("#username").val(),
                   password1 : $("#password1").val(),
                   password2 : $("#password2").val(),
                   email1 : $("#email1").val(),
                   email2 : $("#email2").val()
                 },
                 function(data){
                           $("#errors").html(data).show("slow");
                   }
                            );
    });
});

In the previous code what did i do ?

  • In the first line we tell javascript to execute a function when the document is ready .
  • That function will execute another one if and only if the element of id = “mysubmit” was clicked .
  • If it was clicked then we’ll send some data to the “rules.php” via POST method .
  • We then retrieve this file and load it inside the element with id=”errors” .

So $.post works as follows :-

  • Its first argument is the server-side script , the second is a map of what will be sent to the script and a callback .
  • This callback function will be executed when the operation is completed and takes one argument which will be considered to be the data retrieved from the script .

Note : while coding this script you should output the result , so loading it into a div using any ajax method will mean something !


 

Comments
  1. GaMaL says:

    great post ya Adham😀

    Keep up the good work, I’m interested in your post.. but I’m afraid that it’s so long for normal readers ..

    Ah, BTW, you can freely join the hackers network here:
    http://n.cat-hackers.net and post your posts beside lots of talented IT geeks in Egypt ..
    And you can check my technical posts there
    egamal.n.cat-hackers.net
    😉

    w Bgada Masha2 ALLAH, keep up the good work🙂

    Salam

  2. GaMaL says:

    In the $.post ()
    the second argument can be
    $(“#sendform”).serialize()
    instead of

    {
    username : $(“#username”).val(),
    password1 : $(“#password1”).val(),
    password2 : $(“#password2”).val(),
    email1 : $(“#email1”).val(),
    email2 : $(“#email2”).val()
    }
    serialize serializes the form to JSON data “Javascript Object Notation”
    {
    name : value,
    .
    .
    .
    }

    Again nice post, waiting for you there ..

  3. 3m masr says:

    Hi .. how happy am i to see such kind words !
    About serialize() i tried it but didn’t work ! .. i copied the code form our first JQuery trial if you can remember it .

    Its my honor to post there .. really , if it is possible , i w’ll be so happy to do it !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s