Yii2 Ajax异步验证表单,用于验证用户输入字符串的合法性

yii2中,ActiveForm默认做了客户端验证,但是表单的提交,却不是无刷新的,自定义的验证规则需要提交后才能验证,这样一来页面就刷新了,体验上就不友好了。也就是常常看到的表单提交后页面会刷新。如果想要开启无刷新的模式,只需要在ActiveForm开始开启enableAjaxValidation即可,下面以具体示例实现介绍:

控制器:


    /**
     * Creates a new SystemMenu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
   
        $model = new SystemMenu();
        if(!$model->sort) $model->sort = 0;

        // 该操作是表单字段失去焦点时异步验证,同时如果直接提交表单,也会先执行该操作进行验证
        $model->load($_POST);
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model);
        }

    //表单提交操作,基本上不需要做改动
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //return $this->redirect(['view', 'id' => $model->id]);
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

模型的验证规则:

/**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'sort'], 'required'],
            [['status','parent_id'], 'required','message'=> \Yii::t('app', '请选择{attribute}')],
            [['parent_id', 'create_time', 'update_time', 'create_user', 'update_user', 'status'], 'integer'],
            [[
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值