CakePHP 2.x CookBook 中文版 第七章 模型 之 数据校验
http://www.cnblogs.com/matchless/archive/2013/02/20/2918541.html
一些规则关键字:
'rule' => 'alphaNumeric',
'rule' => 'email',
'rule' => 'date',
'rule' => array('between', 5, 15),
'rule' => array('minLength', '8'),
'rule' => array('maxLength', '8'),
'required' => true,
'allowEmpty' => true
一个例子:
class User extends AppModel {
public $validate = array(
'login' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email' => 'email',
'born' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
)
);
}
1.简单的验证:
class User extends AppModel {
public $validate = array(
'login' => 'alphaNumeric',
'email' => 'email',
'born' => 'date'
);
}
2.一个字段的多个验证规则
public $validate = array(
'enp_name' => array(
"minLength"=>array(
"rule"=>array("minLength",1),
"message"=>"至少输入一个文字"
),
"maxLength"=>array(
"rule"=>array("maxLength",3),
"message"=>"名称的个数不能大于3个"
)
)
);
3.单个规则:每个列一个规则
public $validate = array(
'fieldName1' => array(
'rule' => 'ruleName', // or: array('ruleName', 'param1', 'param2' ...)
'required' => true,
'allowEmpty' => false,
'on' => 'create', // or: 'update'
'message' => 'Your Error Message'
)
);
4.多个规则
public $validate = array(
'fieldName' => array(
'ruleName' => array(
'rule' => 'ruleName',
// 类似 on,required 等扩展键放在这里...
),
'ruleName2' => array(
'rule' => 'ruleName2',
// 类似 on,required 等扩展键放在这里...
)
)
);
5.自定义校验规则
A:自定义校验正则表达式
public $validate = array(
'login' => array(
'rule' => '/^[a-z0-9]{3,}$/i',
'message' => 'Only letters and integers, min 3 characters'
)
);
B:添加自己的校验方法
class User extends AppModel {
public $validate = array(
'promotion_code' => array(
'rule' => array('limitDuplicates', 25),
'message' => 'This code has been used too many times.'
)
);
public function limitDuplicates($check, $limit) {
// $check 的值: array('promotion_code' => 'some-value')
// $limit 的值: 25
$existing_promo_count = $this->find('count', array(
'conditions' => $check,
'recursive' => -1
));
return $existing_promo_count < $limit;
}
}
6.动态改变校验规则
A:添加新的校验规则
$this->validator()->add('password', 'required', array(
'rule' => 'notEmpty',
'required' => 'create'
));
B:链式多次调用 add 来创建多条所需的规则
// 在模型类中
$this->validator()
->add('password', 'required', array(
'rule' => 'notEmpty',
'required' => 'create'
))
->add('password', 'size', array(
'rule' => array('between', 8, 20),
'message' => 'Password should be at least 8 chars long'
));
C:一次性为单个列添加多条规则
$this->validator()->add('password', array(
'required' => array(
'rule' => 'notEmpty',
'required' => 'create'
),
'size' => array(
'rule' => array('between', 8, 20),
'message' => 'Password should be at least 8 chars long'
)
));