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