jQuery 如何打开/关闭 yii2 中某些字段的前端表单验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28857604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:32:16  来源:igfitidea点击:

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

jqueryvalidationyii2

提问by Сергей Илларионов

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 jquery file. All is ok. But when I submit form - hidden fields stay without validation and nothing is happend.How I can kill ofrontend validation, when fields are hiiden and switch on it, when fields are visible?

我在 yii2 视图中遇到了困难的形式,其中一些字段显示或隐藏。它从用户字段选择中决定,在表单中选择选项。我用自定义 jquery 文件编写了这个前端逻辑。一切正常。但是当我提交表单时 - 隐藏的字段没有验证并且什么也没有发生。我怎么能杀死前端验证,当字段隐藏并打开它时,当字段可见时?

回答by Max Wen

$form->field($model, 'youAttribute', ['enableClientValidation' => false])->textInput();

The ActiveFieldclass has a property enableClientValidation, you can simply set this property to falseif you want to disable clientValidation form some fields.

ActiveField班有一个属性enableClientValidation,你可以简单地设置该属性false,如果你想禁用clientValidation形式的某些字段。

回答by Rasikh Mashhadi

To disable client side validation. Begin your active form like this.

禁用客户端验证。像这样开始你的活动形式。

ActiveForm::begin(['enableClientValidation'=>false]);

回答by Nurbek Nurjanov

You can set your active field using this code: (not active record, activefieldexactly)

您可以使用以下代码设置您的活动字段:(不是active recordactivefield完全是)

$activeField = $form->field($model, 'someField');
$activeField->enableClientValidation=false;
$activeField ->enableAjaxValidation=false;

回答by Felipe Almeida

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 validationwith "whenClient"option when defining you validators:

您还可以在定义验证器时使用带有选项的条件客户端"whenClient"验证:

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';
    }"],
]

如果您还需要支持客户端条件验证,则应配置 whenClient 属性,该属性采用表示 JavaScript 函数的字符串,其返回值决定是否应用规则。例如,

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

回答by hesselek

To remove a field from validation:

从验证中删除字段:

$('#yourFormID').yiiActiveForm('remove', 'yourinputID');

To add a field to validation list:

将字段添加到验证列表:

$('#yourFormID').yiiActiveForm('add', {
id: 'country',
        name: 'yourinputID',
        container: '.field-inputID', //or your cllass container
        input: '#yourinputID',
        error: '.help-block',  //or your class error
        validate:  function (attribute, value, messages, deferred, $form) {
            yii.validation.required(value, messages, {message: "Validation Message Here"});
        }
    }); 

And don't forget conditional validation in your model. More info

并且不要忘记模型中的条件验证。 更多信息

回答by gvanto

For your Form, use whenClient:

对于您的表单,请使用 whenClient:

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

And in ut_utils (JS):

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

您还需要添加“何时”来验证服务器端,您也可以在此处添加特定逻辑或使用场景从验证中排除属性...