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

后端 未结 6 1359
滥情空心
滥情空心 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:51

    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 ...

提交回复
热议问题