YII2.0 中如何自定义校验表单规则

本文详细介绍了如何在PHP的CodeIgniter框架中修改models下的companies.php文件,实现公司创建日期的验证,并整合Ajax验证功能。通过在_form.php文件中启用Ajax验证,确保前端操作与后端数据验证的无缝对接。同时,控制器文件中的验证逻辑被优化,以适应Ajax请求的响应方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 修改models下的companies.php

 

/**
*
 @inheritdoc
*/public function rules()
{
    return [
        [['company_name' , 'company_email', 'company_address', 'company_start_date' , 'company_created_date', 'company_status'], 'required'],
        [['company_start_date' , 'company_created_date'], 'safe'],
        [['company_start_date' ],'checkDate'],
        [['company_status' ], 'string'],
        [['company_name' , 'company_email', 'company_address'], 'string', 'max' => 255]
    ];
}

 

 

public function checkDate ($attribute, $params){
   
 $today =date('Y-m-d' );
   
 $selectedDate =date($this ->company_start_date);
   
 if ($selectedDate> $today){
       
 $this ->addError( $attribute,'company start Date must be smaller !');
    }
}

 

     2.修改_form.php文件

# code ...

<?php $form = ActiveForm:: begin(['enableAjaxValidation' =>true]); ?>

# code ...

 

     3.修改控制器文件

/**
* Creates a new Companies model.
* If creation is successful, the browser will be redirected to the 'view' page.
*
 @return mixed
*/

public function actionCreate()
{
   
 $model = new Companies ();

   
 if (Yii:: $app->request ->isAjax && $model->load ($_POST)){
       
 Yii ::$app-> response->format ='json';
       
 return ActiveForm ::validate( $model);
    }

 


    if ($model-> load(Yii ::$app-> request->post ()) && $model->save ()) {
       
 return $this ->redirect([ 'view', 'id' => $model->company_id ]);
    }
 else {
       
 return $this ->render( 'create', [
           
 'model' => $model,
        ]);
    }
}

来自于datou:https://github.com/datou-leo/ci

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值