如何为yii2中的某些字段打开\ off前端表单验证?

Сер*_*нов 10 validation jquery yii2

我在yii2视图中遇到了困难的形式,其中一些字段显示或隐藏.它根据用户字段选择决定,在表单中选择选项.我用自定义jquery文件编写这个前端逻辑.一切都好.但是当我提交表单时 - 隐藏的字段保持不经过验证而且没有任何事情发生.如果字段是hiiden并且打开它,当字段可见时,我如何能够终止验证?

Max*_*Wen 26

$form->field($model, 'youAttribute', ['enableClientValidation' => false])->textInput();
Run Code Online (Sandbox Code Playgroud)

ActiveField班有一个属性enableClientValidation,你可以简单地设置该属性false,如果你想禁用clientValidation形成一些领域.


Ras*_*adi 17

禁用客户端验证.像这样开始你的活动表格.

ActiveForm::begin(['enableClientValidation'=>false]);
Run Code Online (Sandbox Code Playgroud)


Nur*_*nov 10

您可以使用以下代码设置活动字段:(不是active record,activefield确切地说)

$activeField = $form->field($model, 'someField');
$activeField->enableClientValidation=false;
$activeField ->enableAjaxValidation=false;
Run Code Online (Sandbox Code Playgroud)


小智 10

To remove a field from validation:

$('#yourFormID').yiiActiveForm('remove', 'yourinputID');
Run Code Online (Sandbox Code Playgroud)

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"});
        }
    }); 
Run Code Online (Sandbox Code Playgroud)

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


Fel*_*ida 8

您可以尝试为未设置的属性设置默认值:

[
  // 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],
]
Run Code Online (Sandbox Code Playgroud)

更多信息在这里

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

从手册:

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

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