如何为yii2中的某些字段打开\ off前端表单validation?
我在yii2视图中遇到了困难的forms,其中一些字段显示或隐藏。 它根据用户字段选择,在表单中选择选项。 我用自定义jquery文件编写这个前端逻辑。 一切都好。 但是当我提交表单时 – 隐藏的字段保持不经过validation而且没有任何事情发生。如果字段是hiiden并且打开它,当字段可见时,我可以杀死内部validation吗?
禁用客户端validation。 像这样开始你的活动表格。
ActiveForm::begin(['enableClientValidation'=>false]);
$form->field($model, 'youAttribute', ['enableClientValidation' => false])->textInput();
ActiveField
类具有属性enableClientValidation
,如果要在某些字段中禁用clientValidation,则可以将此属性设置为false
。
您可以使用以下代码设置活动字段:(非active record
,完全是活动字段)
$activeField = $form->field($model, 'someField'); $activeField->enableClientValidation=false; $activeField ->enableAjaxValidation=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], ]
更多信息在这里
在定义validation器时,您还可以使用带有"whenClient"
选项的条件客户端validation:
从手册:
如果还需要支持客户端条件validation,则应配置whenClient属性,该属性采用表示JavaScript函数的字符串,其返回值确定是否应用规则。 例如,
[ ['state', 'required', 'when' => function ($model) { return $model->country == 'USA'; }, 'whenClient' => "function (attribute, value) { return $('#country').val() == 'USA'; }"], ]
要从validation中删除字段:
$('#yourFormID').yiiActiveForm('remove', 'yourinputID');
要向validation列表添加字段:
$('#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"}); } });
并且不要忘记模型中的条件validation。 更多信息