当用户注册我的应用程序时,会在提交之前调用以下验证规则:
public function rules()
{
return array(
array('email, firstName, lastName, password, passwordConfirm, telephone', 'required'),
array('club, email, firstName, lastName, level, password, telephone', 'length', 'max'=>45),
array('passwordConfirm', 'compare', 'compareAttribute'=>'password', 'on'=>'register'),
array('email', 'isUniqueEmailAddress'),
);
}
前三个验证规则成功完成,但第四个(自定义验证方法)未成功完成。它应该调用函数“isUniqueEmailAddress”并执行以下操作:
/*
* Returns true if there doesn't exist a user in the database with the submitted email
*/
public function isUniqueEmailAddress($attribute, $params)
{
//if (User::model()->find('email=:email', array(':email'=>$this->email)) !== null)
//{
$this->addError('email', 'Email account already exists');
//}
}
正如您所看到的,我什至注释掉了所有逻辑,以确保将验证错误发送回注册表单,但validation() 上不会返回任何错误。我读过Yii's Documentation并浏览了论坛,但无法理解为什么我的自定义验证方法没有被调用?
最佳答案
在调用 $model->save() 后尝试在 Controller 中设置闪存消息时,我遇到了这个问题。这是代码格式问题导致逻辑错误。
例如,在模型中我有这样的内容:
public function validateNumItems($attribute, $params) {
$this->addError($attribute, 'Validate Items Failed');
}
理论上,出于调试目的,这应该会导致每次表单提交失败。但它从来没有这样做过。
我的 Controller 的更新操作如下所示:
public function actionUpdate($id) {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Collection']))
{
$model->attributes = $_POST['Collection'];
if ($model->save())
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('index'));
}
$this->render('update', array('model' => $model, ));
}
当我添加新行时,Gii 创建的 $model->save() 测试周围缺少括号导致逻辑错误。将支架固定到位。
public function actionUpdate($id) {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Collection'])) {
$model->attributes = $_POST['Collection'];
if ($model->save()) {
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('index'));
}
}
$this->render('update', array('model' => $model, ));
}
关于php - Yii 自定义验证规则未在 validate() 上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203494/