假设我有一个相当典型的按文档验证数组,我想保留这些规则并为 8 多个其他字段添加特定的验证规则。
原文$validate
:
var $validate = array(
'name' => array(
'notEmpty'=> array(
'rule' => 'notEmpty',
'message' => 'Name can not be blank.'
),
'allowedCharacters'=> array(
'rule' => '|^[a-zA-Z ]*$|',
'message' => 'Name can only be letters.'
),
'minLength'=> array(
'rule' => array('minLength', 3),
'message' => 'Name must be at least 3 characters long.'
),
'maxLength'=> array(
'rule' => array('maxLength', 255),
'message' => 'Name can not be longer that 255 characters.'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This E-mail used by another user.'
)
)
);
我可以将以下规则添加到验证数组中,但我不想重复 8 次。
////fragment of array
'field1' => array(
'greaterThanField' => array(
'rule' => array('greaterThanField', 'age'),
'message' => 'This field cannot be greater than age'
)
)
////
function greaterThanField( $field=array(), $compare_field=null ){
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 > $v2) {
return false;
} else {
continue;
}
}
return true;
}
我想添加一个字段名称数组,所有这些字段名称都将使用相同的规则和消息进行评估。我尝试在模型中创建一个变量,然后在 beforeValidate 函数上运行代码,但 beforeValidate 似乎无法访问 compareFields 变量
var $compareFields = array('field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', 'field8');
function beforeValidate(){
foreach ($compareFields as $field) {
$validate[$field] = array(
'rule'=> array('greaterThanField', 'age' ),
'message'=>'Cannot exceed delivery age',
);
}
}
实现这一目标的正确方法是什么?