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

后端 未结 6 1464
傲寒
傲寒 2021-02-20 01:44

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 02:08

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

提交回复
热议问题