How to switch on\off frontend form validation for some fields in yii2?

后端 未结 6 1378
滥情空心
滥情空心 2021-02-19 23:26

I have got difficult form in yii2 view, where some fields show or hide. It decide from user field choises, select options in the form. I write this frontend logic with custom jq

6条回答
  •  心在旅途
    2021-02-19 23:47

    You can try setting default values for attributes that aren't set:

    [
      // set "username" and "email" as null if they are empty
      [['username', 'email'], 'default'],
    
      // set "level" to be 1 if it is empty
      ['level', 'default', 'value' => 1],
    ]
    

    more info here

    You can also use conditional client-side validation with "whenClient" option when defining you validators:

    From the manual:

    If you also need to support client-side conditional validation, you should configure the whenClient property which takes a string representing a JavaScript function whose return value determines whether to apply the rule or not. For example,

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

提交回复
热议问题