yii中异步验证和自定义方法验证


一、异步验证,一般使用ajax验证唯一性较多
1、model开启验证
[['mobile_id','ip'], 'unique','message'=>Yii::t('app','E10010')],
2、控制器验证方法
//ajax异步验证唯一
if (Yii::$app->request->isAjax && Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
$params = Yii::$app->request->post('CardNumber');
$valiArr = ['mobile_id']; //根据一些条件判断,此次请求哪些字段要验证
return ActiveForm::validate($model,$valiArr);
}
3、视图层开启异步验证
<?= $form->field($model, 'mobile_id', [
'enableAjaxValidation' => true,
]);
?>


二、自定义验证方法
在调用$models->validate()方法时会触发自定义方法验证字段
模型层
['idinfobind', 'checkIdInfoBind', 'on' => 'add'],
public function checkIdInfoBind($attribute)
{
$where = Yii::$app->request->post()['Unit']['idinfobind'];
$namedata = Top::find()->where(['id' => $where])->one();
// $studentiddata = Top::find()->where(['student_id' => $where])->one();
if (empty($namedata) ) {
$this->addError($attribute, Yii::t('app', 'user id info bind failed'));//添加错误信息
}

}
原文地址:https://www.cnblogs.com/fwqblogs/p/11077835.html