1、异步验证,通常使用ajax验证惟一性较多
一、model开启验证
[['mobile_id','ip'], 'unique','message'=>Yii::t('app','E10010')],
二、控制器验证方法
//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);
}
三、视图层开启异步验证
<?= $form->field($model, 'mobile_id', [
'enableAjaxValidation' => true,
]);
?>
2、自定义验证方法
在调用$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'));//添加错误信息 } }