在Web建站中,表单的合法性验证是十分重要的一个环节,其中包括客户端浏览器的Javascript的验证和服务端的验证。在本文中将指导读者使用 jQuery中的validate验证框架实现浏览器端的验证代码编写工作,validate框架是一个十分简单实用的验证框架,能大大提高客户端验证代 码的的编写工作,同时,本文使用的是php中十分流行的CodeIgniter框架进行服务端的验证编写工作。本文阅读对象为对jQuery及对PHP CodeIgniter框架有一定认识的读者。

  准备工作

  我们必须下载CodeIgniter及jQuery,版本如下:

  1.CodeIgniter 2.0.2(下载地址:http://codeigniter.com/downloads/)

  2.jQuery 1.6.1 (下载地址:http://code.jquery.com/jquery-1.6.1.min.js)

  3.jQuery validate框架,(下载地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation/)

  设置CodeIgniter

  我们需要自动加载url并且需要使用CodeIgniter中的form表单助手类,所以我们在应用的autoload.php中的第67行添加如下代码:禁止无线网卡连接tp-link的方法

  $autoload['helper'] = array('url', 'form');
  建立视图层文件

  接下来,我们开始编写页面的HTML页代码,我们将用户填写的表单命名为form_view,当校验成功提交后,如果没任何错误,则显示成功提示信息的页面命名为success_view,当然,我们先编写页面的头部和尾部的代码如下:

  Views/common/Header.php:

  <!DOCTYPE>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Form Validation - Gazpo.com</title>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style.css" />
        <script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
        <script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
        <script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>
 
    </head>
    <body>
        <div id="wrapper"> <!-- close it in footer -->
      在header.php中,我们引入了必须引入的jquery类库和jquery validate框架类库文件。

  Views/common/footer.php

   <div id="footer">
             Tutorial by Gazpo.com.

        </div>DevExpress控件使用技巧
    </div>  <!-- /wrapper  -->
    </body> <!-- closing body -->
</html>
  在form_view.php用户填写的表单页中,我们引入了CodeIgniter框架提供的表单助手类,

  利用了其中的form_open标签,代码如下:

<!-- include header -->
<?php $this->load->view('common/header'); ?>
 
    <!-- CodeIgniter Form tag -->
    <?php $attributes = array('id' => 'form');
          echo form_open('form/process', $attributes); ?>
 
    <h2>Form Validation with CodeIgniter and jQuery</h2>
 
    <div class="field">
    <label for="name">Name</label>
    <input class="input" id="name" name="name" type="text" />
    </div>
 
    <div class="field">
    <label for="password">Password</label>
    <input class="input" id="password" name="password" type="password" />
    </div> 
 
    <div class="field">
    <label for="email">Email</label>
    <input class="input" id="email" name="email" type="text" />
    </div>    
 
    <div class="field">
    <label for="gender">Select Gender</label>
    <div class = "gender-fields">
    <input type="radio" class="radio" name="gender" value="male">Male
    <input type="radio" class="radio" name="gender" value="female">Female
    </div>
    </div> 
 
    <div class="field">
    <label for="state">Select State</label>
    <select class="state" name="state">
        <option class="droplist" ></option>
        <option class="droplist" >Alabama</option>
        <option class="droplist" >Alaska</option>
        <option class="droplist" >Arizona</option>
    </select>
    </div>
 
    <div class="field">
    <label for="agree">Terms</label>
    <input type="checkbox" class="checkbox" name="terms" value="agree" />
    </div>
 
    <input type="submit" name="submit" class="submit" value="Submit">
    </form>
 
<!-- include footer -->
<?php $this->load->view('common/footer'); ?>
  Views/success_view.php

<!-- load header -->
<?php $this->load->view('common/header'); ?>
 
<!-- main content -->
<h3>Form was submitted successfully! </h3>
 
<!-- load footer -->
<?php $this->load->view('common/footer'); ?>
  在显示成功页面中,只是简单显示一句成功提交的信息即可。
设置CSS

  下面为了表单的美观,我们设置一下CSS,注意我们使用的是CSS3,代码如下:

  body {

  font-family: arial,verdana,sans-serif;

  color:#333333;

  font-size:13px;

  margin: 0 auto;

  background: #f5f5f5;

  }

  #wrapper {

  margin: 0 auto;

  position: relative;

  background:#FFFFFF;

  width: 900px;

  border:10px solid #eaeaea;

  }

  #form {

  padding: 10px;

  }

  #form .field {

  margin-bottom:15px;

  }

  #form label{

  display: block;

  float: left;

  font-weight: bold;

  margin-right:10px;

  text-align: right;

  width: 120px;

  line-height: 35px;

  font-size:14px;

  cursor: pointer;

  }

  #form .checkbox{

  margin-top:10px;

  }

  #form .input{

  -moz-border-radius: 7px;

  -webkit-border-radius: 7px;

  background-color: #eaeaea;

  background: -moz-linear-gradient(top, #ffffff, #f2f2f2);

  background: -webkit-gradient(linear, left top, left bottom,

  color-stop(0.0, #ffffff), color-stop(1.0, #f2f2f2));

  border: 1px solid #cacaca;

  font-family: inherit;

  color: #797979;

  font-size: 15px;

  padding: 8px 10px;

  width: 300px;

  font-weight: bold;

  }

  #form .state{

  border: 1px solid #b9bdc1;

  padding: 5px;

  font-size: 15px;

  font-family: inherit;

  font-weight: bold;

  color: #797979;

  }

  #form :focus{

  -webkit-box-shadow: 0px 0px 4px #aaa;

  -moz-box-shadow: 0px 0px 4px #aaa;

  box-shadow: 0px 0px 4px #aaa;

  }

  #form .gender-fields{

  padding-top:10px;

  }

  #form span.error {

  color:red;

  padding-left:10px;

  }

  #form .info{

  margin-left:130px;

  font-size: 12px;

  font-style:italic;

  color: #999;

  }

  #form .submit{

  -moz-border-radius: 15px;

  -webkit-border-radius: 15px;

  font-family: arial,verdana,sans-serif;

  background-color: #dedede;

  background: -moz-linear-gradient(top, #ffffff, #eaeaea);

  background: -webkit-gradient(linear, left top, left bottom,

  color-stop(0.0, #ffffff), color-stop(1.0, #eaeaea));

  border: 1px solid #dedede;

  color: #484848;

  font-size:14px;

  font-weight: bold;

  padding: 8px 10px;

  cursor: pointer;

  margin-left:220px;

  }

  /*-- Table design to display data in success view --*/

  #display_data{

  padding:10px;

  }

  #display_data .name{

  font-style: italic;

  text-decoration:underline;

  }

  #display_data table{

  border:1px solid #e5eff8;

  margin:10px 0px;

  border-collapse:collapse;

  }

  #display_data tr.even{

  background:#f7fbff

  }

  #display_data tr.odd .title {

  background:#f4f9fe;

  }

  #display_data td {

  border-bottom:1px solid #e5eff8;

  border-right:1px solid #e5eff8;

  color:#678197;

  padding:5px 8px;

  }

  #display_data td.title{

  font-weight: bold;

  width:100px;

  text-align:right;

  }

  #display_data td.info{

  font-style: italic;

  width:200px;

  }

  #footer {

  width:60%;

  margin:20px auto;

  }
编写CodeIgniter的控制层文件

  接下来,我们要在CodeIgniter中编写控制层文件,以加载视图文件,将控制层文件命名为form.php,放在applications/controller文件夹中,代码为:

  class Form extends CI_Controller {

  public function index()

  {

  $this->load->view('form_view');

  }
  现在,我们已经可以看下表单的效果了,在浏览器中输入如下URL访问:

  http://localhost/form_validation/index.php/form
    设置jQuery Validate插件进行验证

  jQuery Validate插件设置了大量常见的验证规则,如验证email,电话,日期等。我们先看下如何定义设置jQuery Validate的验证规则,比如定义了两个规则,分别验证用户名和email:

 email: {

  required: true,

  email: true

  },

  name: {

  required: true,

  minlength: 3,

  maxlength:25,

  },


  其中,required属性设置为true,表明该字段需要进行验证。比如这里设置了名称字段需要验证,最小输入的长度为3,最长的长度为 25。而如果我们要新增加自己的校验规则,比如要名称字段只能输入的是字母,则可以编写自己的校验方法,并且使用正则表达式,代码如下:

 $.validator.addMethod("lettersonly", function(value, element) {

  return this.optional(element) || /^[a-z]+$/i.test(value);

  }, "Please enter only letters");


  这里,通过addMethod方法,增加了一个名为lettersonly的校验方法,并且使用正则表达式。下面是完成的一个js校验文件,如下:  

(document).ready(function() {

  jQuery.validator.addMethod("lettersonly", function(value, element) {

  return this.optional(element) || /^[a-z]+$/i.test(value);

  }, "Please enter only letters");

  // validate contact form on keyup and submit

  $("#form").validate({

  //set the rules for the fild names

  rules: {

  name: {

  required: true,

  minlength: 3,

  maxlength:25,

  lettersonly: true

  },

  email: {

  required: true,

  email: true

  },

  password: {

  required: true,

  minlength: 5,

  maxlength:15

  },

  gender : {

  required :true

  },

  state : {

  required :true

  },

  agree : {

  required :true

  },

  },

  //设置错误信息

  messages: {

  name: {

  required: "Name is required..",

  },

  password: {

  required: "Please provide a password.",

  minlength: "Password must be at least 5 characters long",

  maxlength: "Password can not be more than 15 characters"

  },

  email: "Valid email is required.",

  agree: "You must agree to our terms.",

  gender: "Gender is required",

  state: "Select state"

  },

  //错误提示信息的放置位置

  errorElement: "span",

  errorPlacement: function(error, element) {

  error.appendTo(element.parent());

  }

  });

  });


  这里,通过设置messages来设置当用户填入非法数据时,要显示的提示信息,而errElement和errorPlacement中,则分别设置了当出现错误时,错误信息追加在页面上显示的位置
服务端CodeIgniter的验证

  接下来,我们要编写服务端的验证。首先,我们要通过引入CodeIgniter中库文件的验证助手类,即:

$this -> load -> library( 'form_validation' );

  然后设置验证规则,比如象名称字段,设置规则为:

$this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[25]' );

  即名称字段必须为字母,最小长度为3,最大长度为25,该字段不能为空。

  当服务端验证通过后,返回到成功页,验证失败后返回到失败提示信息页,如下:

 if ( $this -> form_validation -> run() === FALSE )

  {

  $this -> load -> view( 'form_view' );

  }

  else

  {

  $this -> load -> view( 'success_view' );

  }


  显示表单的错误信息

  我们再在表单的每个字段中,添加显示服务端验证的出错信息的代码,比如:  

  Name

    

  CodeIgniter默认显示表单错误信息是用段落的形式,不大友好,我们修改下验证助手的设置方法,设置成在每个表单字段后,用进行分隔,即: 

$this -> form_validation -> set_error_delimiters('', '');

  在通过了客户端浏览器及服务端的双重验证后,就可以提交数据,保存到数据库了,我们这个例子中不保存到数据库,只是简单再次罗列出来,代码如下: 

$this -> name = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );

  $this -> email = $this -> security -> xss_clean( $this -> input -> post( 'email' ));

  //load the data

  $data['name'] = $this -> name;

  $data['password'] = $this -> password;

  $this -> load -> vars( $data );

  $this -> load -> view( 'success_view' );


  注意这里,我们还调用了xss_clean方法防止跨站RSS攻击。

  最后,完成的控制层代码如下: 

 application/controllers/form.php

  

  class Form extends CI_Controller {

  public function index()

  {

  $this->load->view('form_view');

  }

  public function process()

  {

  $this -> load -> library( 'form_validation' );

  $this -> form_validation -> set_error_delimiters('', '');

  $this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[15]' );

  $this -> form_validation -> set_rules( 'password', 'Password', 'trim|required|min_length[4]|max_length[15]' );

  $this -> form_validation -> set_rules( 'email', 'Email address', 'trim|required|valid_email' );

  $this -> form_validation -> set_rules( 'gender', 'Gender', 'required' );

  $this -> form_validation -> set_rules( 'state', 'State', 'required' );

  $this -> form_validation -> set_rules( 'terms', 'Terms', 'required' );

  //设置校验显示信息

  $this -> form_validation -> set_message( 'min_length', 'Minimum length for %s is %s characters');

  $this -> form_validation -> set_message( 'max_length', 'Maximum length for %s is %s characters');

  if ( $this -> form_validation -> run() === FALSE )

  {

  $this -> load -> view( 'form_view' );

  }

  else

  {

  $this -> name = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );

  $this -> password = $this -> security -> xss_clean( $this -> input -> post( 'password' ) );

  $this -> email = $this -> security -> xss_clean( $this -> input -> post( 'email' ));

  $this -> gender = $this -> input -> post( 'gender' );

  $this -> state = $this -> input -> post( 'state' );

  $this -> terms = $this -> input -> post( 'terms' );

  $data['name'] = $this -> name;

  $data['password'] = $this -> password;

  $data['email'] = $this -> email;

  $data['gender'] = $this -> gender;

  $data['state'] = $this -> state;

  $data['terms'] = $this -> terms;

  //load the data and success view.

  $this -> load -> vars( $data );

  $this -> load -> view( 'success_view' );

  }

  }

  }
当用户的输入完全正确后,success_view的视图页面代码如下所示,显示用户输入的字段信息: 

views/success_view.php

  load->view('common/header'); ?>

  Thank you,

  Form was submitted successfully!

  We have received following data:

  Your name:

  Email:

  Password:

  Gender:

  State:

  Terms:

  load->view('common/footer'); ?>

只有注册用户登录后才能发表评论。
网站导航:

posts - 139, comments - 0, trackbacks - 0, articles - 0

Copyright © PHP博客