YII2 unique怎么才能直接在view下直接验证,并显示错误信息?

这唯一性验证怎么才能在view直接验证,我现在只能post到控制器里面validate后才能显示才能获取到错误信息。

public function rules()
    {
        return [
            [['username'], 'unique', 'message' => '{attribute}已存在'],
            [['mobile'], 'match' ,'pattern' => '/^1[0-9]{10}$/' ,'message' => '{attribute}必须为1开头的11位纯数字' ]
            [['mobile'], 'unique', 'message' => '{attribute}已存在']
        ];
    }
阅读 5k
1 个回答

开启ActiveForm的enableAjaxValidation吧,这样在表单输入之后就会请求服务器端,在服务端返回验证结果:

if (Yii::$app->getRequest()->isAjax
    && $model->load(Yii::$app->getRequest()->post())) {

    Yii::$app->getResponse()->format = Response::FORMAT_JSON;
    /*ActiveForm::validate*/
    echo json_encode(ActiveForm::validate($model));
    Yii::$app->end();//terminate the application
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进