I want to change scenario in view page by jQuery. There is a checkbox in my form, I want inputbox be required in checked checkbox.
my rule:
public function rules() {
return [
.
.
.
['pass' , 'required', 'on'=> 'checked']
]
}
my view page:
<?=$form->field($model, 'check')->checkbox()?>
<?=$form->field($model, 'Pass')->textInput(['maxlength' => 20])?>
Try to set up your rule like this:
public function rules() {
$checkBoxID = Html::getInputId($this, 'check');
return [
/* other rules */
['pass' , 'required',
'when' => function($model) {
return $model->check;
},
'whenClient'=> "function(attribute, value){
return $('#{$checkBoxID}').prop('checked');
}",
'on' => 'checked'
],
];
}
Read about conditional validation and whenClient validator property . Also consider naming you scenario more informative, eg by its purpose, like 'on' => 'sign-up'
, or 'on' => 'login'
. Scenario is useful when you need certain rules to apply in particular cases, but you need to specify this scenario explicitly. Either when you instantiate a model
$model = new MyModel();
$model->scenario = 'sign-up';
and passing it into a view, or before doing any validation after $model->load($data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.