如何为 yii2 中的某些字段切换 on\off 前端表单验证?

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

我在 yii2 视图中遇到困难的表单,其中一些字段显示或隐藏。它由用户字段选择决定,select 表单中的选项。我用自定义 jquery 文件编写了这个前端逻辑。一切正常。但是当我提交表单时 - 隐藏字段没有验证并且什么都没有 happend.How 我可以终止前端验证,当字段隐藏并打开它时,当字段可见时?

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

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

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

[
  // 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

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

来自手册:

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

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

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

要从验证中删除字段:

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

要将字段添加到验证列表:

$('#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"});
        }
    }); 

并且不要忘记模型中的条件验证。 More info

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

ActiveFieldclass有一个属性enableClientValidation,如果要禁用,只需将这个属性设置为false即可clientValidation 形成一些字段。

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

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

并在 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');
    },

您也需要添加 'when' 来验证服务器端您可以在此处添加特定逻辑或使用场景来排除属性被验证...