yii2 ActiveForm验证唯一性
模型
public function rules()
{
return [
[['user_id', 'status','created_at', 'updated_at','company_info_id','main_id'], 'integer'],
['title', 'unique' , 'targetClass' => '\common\models\recruit\Recruit_company_trade', 'message' => '公司名称无效 ! (已存在)'],
[['trade_befor','trade_after','problem','trade_id'],'string'],
[['good'],'integer'],
];
}
title
要验证的字段
unique
验证是否唯一
exist
验证是否存在
targetClass
要验证的模型
message
条件为真提示
控制器
引入 use yii\bootstrap\ActiveForm;
if ($model->load(Yii::$app->request->post())) { //加载模型
if (Yii::$app->request->isAjax) {//验证是否ajax
Yii::$app->response->format = Yii::$app->Response::FORMAT_JSON; //设置返回类型
return ActiveForm::validate($model); //验证模型
} //ajax提交过来的会直接进行验证
}
视图
'enableAjaxValidation' => true,
开启ajax验证
<?php $form = ActiveForm::begin([
'id' => 'company_info',
'options' => ['class' => 'userinfo-edit-form-2'],
'enableAjaxValidation' => true,
'action' => '/artuns/recruitment/company_verif/first'
]); ?>