Yii2 模型自定义验证方法/函数不起作用

Yii2 model custom validate method / function does not work

我想根据 2 个输入 日期 验证我的 fine_amount。但它不会 return 任何错误。在不验证此方法的情况下,它保存了数据。 我也调查了

Yii2: how to use custom validation function for activeform? 但对我来说没有解决方案。

下面是我的代码

Controller method

    $model = $this->findModel($id);

    $model->payment_date=date('d-M-Y',strtotime($model->payment_date));
    $model->payment_expected_date=date('d-M-Y',strtotime($model->payment_expected_date));

    if ($model->load(Yii::$app->request->post())) {
        $model->payment_date=date('Ymd',strtotime($model->payment_date));
        $model->payment_expected_date=date('Ymd',strtotime($model->payment_expected_date));

        if($model->validate()){
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }
        else{
            $model->payment_date=date('d-M-Y',strtotime($model->payment_date));
            $model->payment_expected_date=date('d-M-Y',strtotime($model->payment_expected_date));

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    return $this->render('update', [
        'model' => $model,
    ]);

My Rule

['fine_amount' , 'fine_required'] ,

Validation function

public function fine_required() {
    $this->payment_date = date ( 'Ymd' , strtotime ( $this->payment_date ) );
    $this->payment_expected_date = date ( 'Ymd' , strtotime ( $this->payment_expected_date ) );

    if ( $this->payment_date > $this->payment_expected_date ) {
        if ( $this->fine_amount <= 0 ) {
            $this->addError ( 'fine_amount' , 'Fine Amount Must be add.' );
        }
        return false;
    }
    return true;
}

您需要针对您的情况使用 conditional validation,分别使用 whenwhenClient 请参阅下面添加到您的规则部分并删除任何其他验证。这将处理前端和后端两个验证

[ 'fine_amount' , 'required' , 'when' => function($model) {
        if ( $model->payment_date > $model->payment_expected_date ) {
            if ( $model->fine_amount <= 0 ) {
                return true;
            }
        }
        return false;
    } , 'whenClient' => 'function (attribute, value) {

    var d1 = new Date($("#' . Html::getInputId($this, 'payment_date') . '").val());
    var d2 = new Date($("#' . Html::getInputId($this, 'payment_expected_date'). '").val());
    if(d1>d2){
        if(value<=0){
            return true;
        }
    }
    return false;
}' , 'message' => 'Fine Amount Must be add.' ] ,

编辑

strtolower ( \yii\helpers\StringHelper::basename ( get_class ( $this ) ) ) 替换为 Html::getInputId,因为它更适合这种情况。