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

后端 未结 6 2408
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 23:10

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-20 00:10

    For your Form, use whenClient:

    ['name', 'required', 'when' => {serverSide Condition),
                'whenClient' => "ut_utils.isAttributeVisible",
            ],
            ['name', 'string', 'min' => 2, 'max' => 28],
            ['name', 'trim'],
    

    And in ut_utils (JS):

    /**
         * Useful for FE validation (whenClient) to validate only if visible (ie valid input)
         *
         * @param attribute  Obj containing all sorts of info about attr including container name :-)
         * @param value
         */
        isAttributeVisible: function (attribute, value) {
            return $(attribute.container).is(':visible');
        },
    

    You will need to add 'when' to validate serverside too you can add specific logic here or use a scenario to exclude attributes from being validated ...

提交回复
热议问题