我们可以创建验证规则吗,它可以作为核心验证规则。
假设我想使用一个可以用于输入字段的验证函数。意味着我有一个类似的功能
function checkinput($input)
{
$arr=array('x','y','z');
if(in_array($input,$arr))
return false;
else
return true;
}
现在我想在所有模型中使用这个函数作为验证。假设已经为这个函数创建了一个自定义规则,名称checkinput。我想在任何模型中使用此验证作为:
var $validate = array(
'name' => array(
'notempty' => array(
'rule' => 'notEmpty',
'message' => 'Please provide a name.',
),
'checkinput' => array(
'rule' => 'checkinput',
'message' => "You can't use X,Y,Z as name.",
),
));
这种自定义验证规则可以通过行为或其他方法创建吗。。
您应该能够将函数放置在app_model.php
(或AppModel.php
,具体取决于您使用的Cake版本。这将使您的所有模型都可以访问该函数进行验证/其他用途。
引用手册:
在查找方法之前,首先检查模型/行为方法在Validation类上。这意味着您可以覆盖现有应用程序级别的验证方法(如alphaNumeric())(通过将方法添加到AppModel),或在模型级别。
这将帮助您:"自定义验证规则"http://www.dereuromark.de/2010/07/19/extended-core-validation-rules/
以及http://www.dereuromark.de/2011/10/07/maximum-power-for-your-validation-rules/github 中的代码
请注意,首先需要array_shift(有关详细信息,请参阅调试输出):
function validateCustom($field) {
$field = array_shift($field);
....
}
我们已经发布了验证规则。这个例子最适合在cakepp中进行验证。
public $validate = array(
'name' => array(
'rule' => array('custom', '/^[a-z0-9]{1,}$/i'),
'message' => 'Alphabets and numbers only'
),
'user_name' => array(
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'The username has already been taken.',
),
'notEmpty' => array(
'rule' => array('custom','/^[a-z0-9]{1,}$/i'),
'message' => 'Alphabets and numbers only',
),
),
/*'password' => array(
'rule' => array('minLength', 6),
'message' => 'Passwords must be at least 6 characters long.',
),*/
'password1' => array(
'password' => array(
'rule' => '/^[a-z0-9]{1,}$/i',
'message' => 'Only letters and integers'
),
'between' => array(
'rule' => array('between', 6, 50),
'message' => 'Between 6 to 50 characters'
),),
'confirm_password' => array(
'equaltofield' => array(
'rule' => array('equaltofield','password1'),
'message' => 'Password does not match.',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
'on' => 'create', // Limit validation to 'create' or 'update' operations
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'The passwords you entered do not match.',
)
),
'email_address' => array(
'email' => array(
'rule' => array('custom','/^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+.)+([A-Za-z0-9]{2,4}|museum)$/i'),
'message' => 'Please provide a valid email address.',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Email address already in use.',
),
)
);
function equaltofield($check,$otherfield)
{
//get name of field
$fname = '';
foreach ($check as $key => $value){
$fname = $key;
break;
}
return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
}
/*public function beforeValidate(){
return true;
}*/
public function validate_passwords() {
return $this->data[$this->alias]['password1'] === $this->data[$this->alias]['confirm_password'];
}