yii2 自定义验证不起作用

yii2 custom validation not working

我需要比较模型中的 2 个属性值,只有当第一个值低于第二个值形式时,才能 validate.I 尝试使用下面的代码,但它不起作用。

控制器

public function actionOpanningBalance(){

     $model = new Bill();
     if ($model->load(Yii::$app->request->post())) {
        $model->created_at = \Yii::$app->user->identity->id;
        $model->save();
      }else{
       return $this->render('OpanningBalance', [
            'model' => $model,
        ]);
     } 
}

型号

public function rules()
{
    return [
        [['outlet_id', 'sr_id', 'bill_number', 'bill_date', 'created_at', 'created_date','bill_amount','credit_amount'], 'required'],
        [['outlet_id', 'sr_id', 'created_at', 'updated_at'], 'integer'],
        [['bill_date', 'd_slip_date', 'cheque_date', 'created_date', 'updated_date','status'], 'safe'],
        [['bill_amount', 'cash_amount', 'cheque_amount', 'credit_amount'], 'number'],
        [['comment'], 'string'],
        ['credit_amount',function compareValue($attribute,$param){
               if($this->$attribute > $this->bill_amount){
               $this->addError($attribute, 'Credit amount should less than Bill amount');
    }],           
        [['bill_number', 'd_slip_no', 'bank', 'branch'], 'string', 'max' => 225],
        [['cheque_number'], 'string', 'max' => 100],
        [['bill_number'], 'unique']
    ];
}
}

它进入了验证器函数,但没有像我想要的那样添加错误

$this->addError($attribute, 'Credit amount should less than Bill amount');

谁能帮我解决这个问题?

试试这个:

public function actionOpanningBalance(){

 $model = new Bill();
 if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    $model->created_at = \Yii::$app->user->identity->id;
    $model->save();
  }else{
   return $this->render('OpanningBalance', [
        'model' => $model,
    ]);
 } 
}

验证

你可以使用匿名函数:

['credit_amount',function ($attribute, $params) {
            if ($this->$attribute > $this->bill_amount)) {
                $this->addError($attribute, 'Credit amount should less than Bill amount.');
              return false;
            }
        }],

你可以像下面这样使用答案也写

public function rules(){
    return [
        ['credit_amount','custom_function_validation', 'on' =>'scenario'];
}
public function custom_function_validation($attribute){
    // add custom validation
    if ($this->$attribute < $this->cash_amount) 
        $this->addError($attribute,'Credit amount should less than Bill amount.');
}

如果验证没有添加任何错误,则很可能被跳过了。这个问题很可能是因为默认规则行为,它跳过空的或已经错误的给定值,如下所示:https://www.yiiframework.com/doc/guide/2.0/en/input-validation#inline-validators

具体来说:

By default, inline validators will not be applied if their associated attributes receive empty inputs or if they have already failed some validation rules. If you want to make sure a rule is always applied, you may configure the skipOnEmpty and/or skipOnError properties to be false in the rule declarations.

因此您需要根据适合您的情况设置 skipOnEmptyskipOnError 值:

[
    ['country', 'validateCountry', 'skipOnEmpty' => false, 'skipOnError' => false],
]

我已经 custom_function_validation 像这样使用第 3 个参数工作:

public function is18yo($attribute, $params, $validator)
{
    $dobDate = new DateTime($this->$attribute);
    $now = new DateTime();
    if ($now->diff($dobDate)->y < 18) {
        $validator->addError($this, $attribute, 'At least 18 years old');
        return false;
    }
}

这是后端验证,只会在提交时触发。所以你可以在你的验证函数中尝试这样的事情。

if (!$this->hasErrors()) {
  // Your validation code goes here.
}

如果您查看生成的 basic Yii2 应用程序,您可以在文件 models/LoginForm.php 中看到该示例,其中有一个名为 validatePassword.

的函数

只有在提交表单后才会触发验证。