yii中異步驗證和自定義方法驗證


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'));//添加錯誤信息 } }
相關文章
相關標籤/搜索