cakephp中擴張自訂驗證規則

來源:互聯網
上載者:User
cakephp中擴充自訂驗證規則
在CAKEPHP中,有多達26條驗證規則可以用,詳細的見這裡:
http://book.cakephp.org/view/1181/Adding-your-own-Validation-Methods#!/view/1152/Core-Validation-Rules

但如何擴充自訂呢?比如一個例子中,只對管理使用者要校正輸入使用者名稱,普通使用者不用
(一個很極端的例子),可以這樣做:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array('notempty' =>
array('rule' => array('notempty'),
'message' => 'Please enter first name',
......

.......
'username' => array('custom' =>
array('rule' => array('validateDependentFields'),
'message' => 'Please enter height',
這裡對username使用自訂的方法,定義一個方法validateDependentFields去校正

方法為:
function validateDependentFields($field){     $passed=true;     switch(true){         case array_key_exists('username',$field):             if(  $this->data['User']['user_type_id']==1 and (!isset($this->data['User']['username']) or empty($this->data['User']['username'])) ){                 $passed=false;             }else{                 $passed=true;             }         break;         case array_key_exists('class_of',$field):             if(  $this->data['User']['user_type_id']==1 and (!isset($this->data['User']['class_of']) or empty($this->data['User']['class_of'])) ){                 $passed=false;             }else{                 $passed=true;             }         break;     }     return $passed; }


這裡假如user_type_id=1為管理員,則返回true,指示使用校正規則;否則就不校正,返回false
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.