qakbar
qakbar

Reputation: 53

How to validate form in jQuery and PHP

I have a registration form that I want to validate using jQuery and than pass it to PHP to login if all details are correct.

I am trying to use Yendesigns form - http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/

My form code is:

<?php

require_once("includes/initialise.php");

if (isset($_POST['resetpassword']) && $_POST['resetpassword'] == 'resetnow') {
    $required = array('first_name','last_name','username','email','password','password2');
    $missing = array();
    $validation = array(
        'first_name'    => 'Please provide your first name',
        'last_name'     => 'Please provide your last name',
        'username'      => 'Please provide your username',
        'email'         => 'Please provide your valid email address',
        'password'      => 'Please provide your password',
        'password2'     => 'Please confirm your password',
        'userdup'       => 'Username already registered',
        'emaildup'      => 'Email address already registered',
        'mismatch'      => 'Passwords do not match'
    );

//Sanitise and clean function
$first_name = escape($_POST['first_name']);
$last_name = escape($_POST['last_name']);
$username = escape($_POST['username']);
$email = escape($_POST['email']);
$password = escape($_POST['password']);
$password2 = escape($_POST['password2']);

    foreach($_POST as $key => $value) {
        $value = trim($value);
        if(empty($value) && in_array($key,$required)) {
            array_push($missing,$key);
        } else {
            ${$key} = escape($value);
        }
    }

    if($_POST['email'] !="" && getDuplicate(1,'email','clients','email',$email)) {
        array_push($missing,'emaildup');
    }

    if($_POST['username'] !="" && getDuplicate(1,'username','clients','username',$username)) {
        array_push($missing,'userdup');
    }

    // Check User Passwords
    if( strcmp($_POST['password'], $_POST['password2']) != 0 ) {
        array_push($missing,'mismatch');
    }

    //validate email address
    if(!empty($_POST['email']) && !isEmail($_POST['email'])) {
        array_push($missing,'email');       
    }

    if(!empty($missing)) {
        $before = " <span class=\"errorred\">";
        $after = "</span>";
        foreach($missing as $item)
            ${"valid_".$item} = $before.$validation[$item].$after;
    } else {    
// stores MD5 of password
$passmd5 = md5($_POST['password']);

// stores clients IP addresss   
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain  like example.com) 
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

$date = date('Y-m-d');
$time = date('H:i:s');

// Generates activation code simple 4 digit number
$hash = mt_rand().date('YmdHis').mt_rand();

//Insert Data
$sql = "INSERT INTO clients(first_name, last_name, username, email, password, date, time, `hash`)
        VALUES ('{$first_name}','{$last_name}','{$username}','{$email}','$passmd5','$date', '$time','$hash')";

$result = mysql_query($sql, $conndb) or die(mysql_error());

if($result)  {

        $to = $_POST['email'];
        $subject = 'Activate your account';
        $from = '[email protected]';

        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: My Website Name <".$from.">\r\n";
        $headers .= "Reply-to: My Website Name <".$from.">\r\n";

        $message = '<div style="font-family:Arial, Verdana, Sans-serif; color:#333; font-size:12px">
        <p>Thank you for registering on our website</p>
        <p>Please click on the following link to activate your account: 

        <a href="http://'.$host.''.$path.'/activate.php?id='.$hash.'">http://'.$host.''.$path.'/activate.php?id='.$hash.'</a></p>

        <p>Here are your login details...</p>
        <p>User Name: '.$username.'</p>
        <p>Email: '.$email.' </p>
        <p>Passwd: '.$password.' </p>

        </p></div>';

        if (mail($to, $subject, $message, $headers)) {

            $confirmation = '<p>Thank you.<br />You have successfully registered.</p>';

        } else {

            $confirmation = '<p>Error.<br />Your activation link could not be sent.<br />Please contact administrator.</p>';
            }
        }
    }
}

require_once("includes/header.php");
?>

        <div class="block">
            <div class="block_head">
                    <div class="bheadl"></div>
                    <div class="bheadr"></div>

                    <h5>Register</h5>

                    <ul>
                        <li><a href="login.php">Login</a></li>
                    </ul>

        </div>      <!-- .block_head ends -->

        <div class="block_content">

      <?php echo isset($confirmation) ? $confirmation : NULL; ?>

    <form name="register" id="customForm" action="" method="post">

        <div>
            <label for="first_name">First Name: * <?php echo isset($valid_first_name) ? $valid_first_name : NULL; ?></label>
            <input id="first_name" name="first_name" type="text" class="fld" value="" />
            <span id="first_nameInfo"></span>
        </div>
        <div>
            <label for="last_name">Last Name: * <?php echo isset($valid_last_name) ? $valid_last_name : NULL; ?></label>
            <input id="last_name" name="last_name" type="text" class="fld" value="" />
            <span id="last_nameInfo"></span>
        </div>
        <div>
            <label for="username">Username: * <?php echo isset($valid_username) ? $valid_username : NULL; ?> <?php if(isset($valid_userdup)) { echo $valid_userdup; } ?></label>
            <input id="username" name="username" type="text" class="fld" value="" />
            <span id="usernameInfo"></span><span id="status"></span>
        </div>
        <div>
            <label for="email">E-mail: * <?php if(isset($valid_email)) { echo $valid_email; } ?> <?php if(isset($valid_emaildup)) { echo $valid_emaildup; } ?></label>
            <input id="email" name="email" type="text" class="fld" value="" />
            <span id="emailInfo"></span>
        </div>
        <div>
            <label for="pass1">Password: * <?php if(isset($valid_password)) { echo $valid_password; } ?></label>
            <input id="pass1" name="pass1" type="password" class="fld" value="" />
            <span id="pass1Info"></span>
        </div>
        <div>
            <label for="pass2">Confirm Password: * <?php if(isset($valid_password2)) { echo $valid_password2; } ?> <?php if(isset($valid_mismatch)) { echo $valid_mismatch; } ?></label>
            <input id="pass2" name="pass2" type="password" class="fld" value="" />
            <span id="pass2Info"></span>
        </div>
        <div>
            <input id="send" name="send" type="submit" value="Send" />
        </div>

        </table>
        <input type="hidden" name="resetpassword" value="resetnow" />
    </form>
</div>  

                <!-- .block_content ends -->

                <div class="bendl"></div>
                <div class="bendr"></div>


                    </div>

<?php
require_once("includes/footer.php");
?>

And the jquery is:

/***************************/
//@Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//@website: www.yensdesign.com
//@email: [email protected]
//@license: Feel free to use it, but keep this credits please!                  
/***************************/

$(document).ready(function(){
    //global vars
    var form = $("#customForm");
    var first_name = $("#first_name");
    var first_nameInfo = $("#first_nameInfo");
    var last_name = $("#last_name");
    var last_nameInfo = $("#last_nameInfo");
    var email = $("#email");
    var emailInfo = $("#emailInfo");
    var pass1 = $("#pass1");
    var pass1Info = $("#pass1Info");
    var pass2 = $("#pass2");
    var pass2Info = $("#pass2Info");
    var message = $("#message");

    //On blur
    first_name.blur(validateName);
    last_name.blur(validateLastName);
    email.blur(validateEmail);
    pass1.blur(validatePass1);
    pass2.blur(validatePass2);
    //On key press
    first_name.keyup(validateName);
    last_name.keyup(validateLastName);
    pass1.keyup(validatePass1);
    pass2.keyup(validatePass2);
    message.keyup(validateMessage);
    //On Submitting
    form.submit(function(){
        if(validateName() & validateLastName() & validateEmail() & validatePass1() & validatePass2() & validateMessage())
            return true
        else
            return false;
    });

    //validation functions
    function validateEmail(){
        //testing regular expression
        var a = $("#email").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        //if it's valid email
        if(filter.test(a)){
            email.removeClass("error");
            emailInfo.text("");
            emailInfo.removeClass("error");
            return true;
        }
        //if it's NOT valid
        else{
            email.addClass("error");
            emailInfo.text("Please provide a valid email address");
            emailInfo.addClass("error");
            return false;
        }
    }
    function validateName(){
        //if it's NOT valid
        if(first_name.val().length < 4){
            first_name.addClass("error");
            first_nameInfo.text("Please provide your first name (more than 3 letters)");
            first_nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else{
            first_name.removeClass("error");
            first_nameInfo.text("");
            first_nameInfo.removeClass("error");
            return true;
        }
    }

    function validateLastName(){
        //if it's NOT valid
        if(last_name.val().length < 4){
            last_name.addClass("error");
            last_nameInfo.text("Please provide your first name (more than 3 letters)");
            last_nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else{
            last_name.removeClass("error");
            last_nameInfo.text("");
            last_nameInfo.removeClass("error");
            return true;
        }
    }
    function validatePass1(){
        var a = $("#password1");
        var b = $("#password2");

        //it's NOT valid
        if(pass1.val().length <5){
            pass1.addClass("error");
            pass1Info.text("Please provide your password (at least 5 characters)");
            pass1Info.addClass("error");
            return false;
        }
        //it's valid
        else{           
            pass1.removeClass("error");
            pass1Info.text("");
            pass1Info.removeClass("error");
            validatePass2();
            return true;
        }
    }
    function validatePass2(){
        var a = $("#password1");
        var b = $("#password2");
        //are NOT valid
        if( pass1.val() != pass2.val() ){
            pass2.addClass("error");
            pass2Info.text("Passwords doesn't match!");
            pass2Info.addClass("error");
            return false;
        }
        //are valid
        else{
            pass2.removeClass("error");
            pass2Info.text("");
            pass2Info.removeClass("error");
            return true;
        }
    }
    function validateMessage(){
        //it's NOT valid
        if(message.val().length < 10){
            message.addClass("error");
            return false;
        }
        //it's valid
        else{           
            message.removeClass("error");
            return true;
        }
    }
});

When I click the submit button the form passes via php and stops the jquery. If the submit button is not pressed than it carries on validating via jQuery.

How can I get it to if all details are correct to pass the PHP validation too. If errors or user has jQuery disabled to validate via PHP?

Thank you

Upvotes: 2

Views: 6350

Answers (3)

Roger
Roger

Reputation: 3256

to insert into a database i use this function.

/**
     * Takes an array or string and takes out malicous code.
     * @param array|string $var
     * @param string $key
     * @return string
     */
    function aspam($var, $returnZero = false, $key = '') {
        if (is_array($var) && !empty($key)) {
            /*
             * if var is array and key is set, use aspam on the array[key]
             * if not set, return 0 or ''
             */
            if (isset($var[$key])) {
                return general::aspam($var[$key], $returnZero);
            } else {
                return ($returnZero) ? 0 : '';
            }
        } elseif (is_array($var) && empty($key)) {
            /*
             * if var is array and key is empty iterate through all the members
             * of the array and aspam the arrays and take out malicous code of the
             * strings or integers.
             */
            $newVar = array();
            $newVal = '';
            foreach ($var as $key => $val) {
                if (is_array($val)) {
                    $newVal = general::aspam($val, $returnZero);
                } elseif (!empty($val)) {
                    $newVal = trim(htmlspecialchars($val, ENT_QUOTES));
                } else {
                    $newVal = ($returnZero) ? 0 : '';
                }
                $newVar[$key] = $newVal;
            }
            return $newVar;
        } elseif (!empty($var)) {
            /*
             * Strip malicous code
             */
            return trim(htmlspecialchars($var, ENT_QUOTES));
        } else {
            /*
             * return default 0 | '' if string was empty
             */
            return ($returnZero) ? 0 : '';
        }
    }

to use this function you put in the array, then tell it if you want to return empty or 0.

$product_id = aspam($_REQUEST, true, 'product_id');

The javascript with jquery you can itterate through a class and validate all at once.

/*variable to check if it is valid*/
        var returnVar = true;
        $('.required').each(function () {
            if ($(this).is("select")) {
                if ($(this).val() > '0') {
                    /*Code for is valid*/
                    $(this).parent().removeClass("alert-danger");
                } else {
                    /*Code for is not valid*/
                    $(this).parent().addClass("alert-danger");
                    returnVar = false;
                }
            } else {
                if (!$(this).val()) {
                    /*Code for is valid*/
                    $(this).parent().addClass("alert-danger");
                    returnVar = false;
                } else {
                    /*Code for is not valid*/
                    $(this).parent().removeClass("alert-danger");
                }
            }
        });
        if(returnVar){
            /*submit form*/
        }

Upvotes: 0

Stefan
Stefan

Reputation: 3900

METHOD 1: In your jQuery (untested):

$("#send").click(function(e) {
    e.preventDefault();
    // call javascript validation functions here
    // if valid then submit form:
    $("#customForm").submit();
});

EDIT: If user has not got javascript, then the form will be submitted as usual and validated by php only when the submit button is clicked. But if javascript is enabled, then the default submit action will be prevented, and you can first check whatever you want to check on the client side before submitting the form.

METHOD 2: Instead of the jQuery code above, you can instead call your javascript validation functions with an onSubmit="return validate();" form attribute, where validate() javascript function returns false if there are errors. This will also prevent the form from submitting directly - unless the user does not have javascript.

UPDATE IN RESPONSE TO ZAFER's COMMENT:

In method 1, might be better to use this instead:

$("#customForm").submit(function(e) {
    e.preventDefault();
    // call javascript validation functions here
    // if valid then submit form:
    $(this).submit();
});

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69260

A good web application has two layers of validation:

  • The input is validated client side with javascript (e.g. jquery). It gives better feedback for the user if the validation is done immediately without contacting the server.
  • The input is validated server side to guard against malicious users having bypassed the client side validation (or simply a user with javascript disabled). There are also cases where validation rules are hard to implement client side.

If you want to test your server side validation, the easiest is probably to temporary disable javascript in the browser.

Upvotes: 1

Related Questions