Yii2方案无效的自定义验证

时间:2016-06-23 05:37:48

标签: yii2

我正在为给定方案创建验证数据的函数,但它不起作用。 型号代码:

public function rules()
    {
        return [
     //   ['session_key','deal_id','required'],
        ['data', 'validateCart'],
        [['session_key','deal_id'], 'safe'],
       // [['cartfood','session_key'], 'required','on'=>'sessionapi'],
        ['cartfood', 'myvalidation', 'on' => 'sessionapi'],
        ];
    }

 public function myvalidation($attribute, $params){
          if (!$this->hasErrors()) { 
            echo '<pre>'; print_r($params); die;
          }
     }

控制器:代码

public function actionPayinapp(){
        $data=Yii::$app->getRequest()->getBodyParams();    
        $cart=json_decode($data['cartfood']);
        $model=new Cart();  
        $model->scenario = 'sessionapi';
        $dataarr = array();
        $model->data = $cart;  
 if($model->validate())
        { 
die(ok);
}
}

我希望myvalidationsessionapi方案上运行,但它无效。

1 个答案:

答案 0 :(得分:2)

将您的控制器代码更改为: - SkipOnEmpty

 public function rules()
{
    return [
        //   ['session_key','deal_id','required'],
        ['data', 'validateCart'],
        [['session_key','deal_id'], 'safe'],
        // [['cartfood','session_key'], 'required','on'=>'sessionapi'],
        //you have to apply skipOnEmpty in your rules as
        ['cartfood', 'myvalidation', 'on' => 'sessionapi' ,'skipOnEmpty' => false],
    ];
}

public function myvalidation($attribute, $params){
    if (!$this->hasErrors()) {
        echo '<pre>'; print_r($params); die;
    }
}