實戰jQuery跟PHP CodeIgniter表單驗證

來源:互聯網
上載者:User
實戰jQuery和PHP CodeIgniter表單驗證
原文發表在 http://tech.it168.com/a2011/0818/1234/000001234617.shtml
上,乃本人作品,轉載請註明:

前言

  在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行添加如下代碼:

  $autoload['helper'] = array('url', 'form');
  建立視圖層檔案

  接下來,我們開始編寫頁面的HTML頁代碼,我們將使用者填寫的表單命名為form_view,當校正成功提交後,如果沒任何錯誤,則顯示成功提示資訊的頁面命名為success_view,當然,我們先編寫頁面的頭部和尾部的代碼如下:

  Views/common/Header.php:




Form Validation - Gazpo.com








在header.php中,我們引入了必須引入的jquery類庫和jquery validate架構類庫檔案。

  Views/common/footer.php


Tutorial by Gazpo.com.





  在form_view.php使用者填寫的表單頁中,我們引入了CodeIgniter架構提供的表單助手類,

  利用了其中的form_open標籤,代碼如下:


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


'form');
echo form_open('form/process', $attributes); ?>

Form Validation with CodeIgniter and jQuery




Name




Password




Email




Select Gender

Male
Female




Select State
Alabama Alaska Arizona



Terms







load->view('common/footer'); ?>
  Views/success_view.php


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


Form was submitted successfully!




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。而如果我們要新增加自己的校正規則,比如要名稱欄位只能輸入的是字母,則可以編寫自己的校正方法,並且使用Regex,代碼如下:

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

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

  }, "Please enter only letters");


  這裡,通過addMethod方法,增加了一個名為lettersonly的校正方法,並且使用Regex。下面是完成的一個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'); ?>


  最後,讀者可以在這裡(http://gazpo.com/gazpo-files/tut10-form/form_validation.zip)下載本文的代碼。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.