Yii2模型自定义验证方法/功能不起作用

时间:2018-03-26 02:36:03

标签: yii2 yii2-model yii2-validation

我想针对2输入日期验证我的 fine_amount 。但它不会返回任何错误。如果不验证此方法,则会保存数据。 我也调查了

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;
}

1 个答案:

答案 0 :(得分:1)

您需要针对您的情况使用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,因为它更适合此案例。