Yii2: Conditional Validator always returns required

前端 未结 5 1468
-上瘾入骨i
-上瘾入骨i 2021-02-07 17:24

I am trying to use Yii2\'s conditional validator as given in the guide like:

Model code

public function rules()
{
   // $discharged = function($model) {          


        
相关标签:
5条回答
  • 2021-02-07 17:39
    ['package_id_fk', 'required', 'when' => function($model) {return $model->type == 'PACKAGE';}, 'enableClientValidation' => false],
    

    It works for me.

    0 讨论(0)
  • 2021-02-07 17:48

    Try to add enableClientValidation parameter as the following:

     ['discharge_date', 'required', 'when' => function($model) {
            return $model->discharged == 1;
     }, 'enableClientValidation' => false]
    
    0 讨论(0)
  • 2021-02-07 17:59

    This only worked for me when using the model name (client validation).

    ['state', 'required', 'when' => function ($model) {
      return $model->country == 'USA';
    }, 'whenClient' => "function (attribute, value) {
      return $('#MODELNAMEHERE-country').val() == 'USA';
    }"]

    0 讨论(0)
  • 2021-02-07 18:02

    i had the similar requirement i solved it using the following code

    ['discharge_date', 'required', 'whenClient' => function($model) {
            return $model->discharged == 1;
     }, 'enableClientValidation' => false]
    
    0 讨论(0)
  • 2021-02-07 18:03

    It seems that by default Yii2 will do validation in BOTH Server side and Client side. Check the example in Conditional Validation part of Yii2 doc:

    ['state', 'required', 'when' => function ($model) {
        return $model->country == 'USA';
    }, 'whenClient' => "function (attribute, value) {
        return $('#country').val() == 'USA';
    }"],
    

    you also need a 'whenClient' code, or as @Alexandr Bordun said, to disable the client validation by 'enableClientValidation' => false.

    0 讨论(0)
提交回复
热议问题