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

查看:303
本文介绍了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}已存在']
        ];
    }

解决方案

开启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
}

这篇关于YII2 unique怎么才能直接在view下直接验证,并显示错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆