如何在jQuery和PHP中验证表单

时间:2012-04-08 17:35:48

标签: php jquery

我有一个注册表单,我想使用jQuery进行验证,如果所有细节都正确,我会将其传递给PHP进行登录。

我正在尝试使用Yendesigns表单 - http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/

我的表单代码是:

<?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 = 'dummy@emailaddress.co.uk';

        $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");
?>

jquery是:

/***************************/
//@Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@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;
        }
    }
});

当我单击提交按钮时,表单通过php传递并停止jquery。如果未按下提交按钮,则继续通过jQuery进行验证。

如果所有细节都正确通过PHP验证,我怎么能得到它。如果错误或用户禁用jQuery以通过PHP验证?

谢谢

3 个答案:

答案 0 :(得分:1)

方法1:在你的jQuery(未经测试)中:

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

编辑:如果用户没有javascript,那么表单将照常提交并仅在单击提交按钮时由php验证。但是如果启用了javascript,则会阻止默认的提交操作,您可以在提交表单之前先检查您要在客户端检查的内容。

方法2:代替上面的jQuery代码,您可以使用onSubmit="return validate();"表单属性调用javascript验证函数,如果有错误,validate() javascript函数返回false。这也会阻止表单直接提交 - 除非用户没有javascript。

响应ZAFER的评论更新:

在方法1中,最好使用它:

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

答案 1 :(得分:1)

一个好的Web应用程序有两层验证:

  • 使用javascript(例如jquery)验证输入的客户端。如果在不联系服务器的情况下立即完成验证,它会为用户提供更好的反馈。
  • 输入是经过验证的服务器端,以防止恶意用户绕过客户端验证(或者只是禁用了javascript的用户)。还有一些情况,验证规则很难实现客户端。

如果您想测试服务器端验证,最简单的可能是在浏览器中暂时禁用javascript。

答案 2 :(得分:0)

要插入数据库,我使用此功能。

/**
     * 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 : '';
        }
    }

使用此函数放入数组,然后告诉它是否要返回空或0。

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

带有jquery的javascript,你可以通过一个类进行迭代并一次验证所有内容。

/*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*/
        }