I am trying to use Yii2\'s conditional validator as given in the guide like:
Model code
public function rules()
{
// $discharged = function($model) {
['package_id_fk', 'required', 'when' => function($model) {return $model->type == 'PACKAGE';}, 'enableClientValidation' => false],
It works for me.
Try to add enableClientValidation parameter as the following:
['discharge_date', 'required', 'when' => function($model) {
return $model->discharged == 1;
}, 'enableClientValidation' => false]
This only worked for me when using the model name (client validation).
['state', 'required', 'when' => function ($model) {
return $model->country == 'USA';
}, 'whenClient' => "function (attribute, value) {
return $('#MODELNAMEHERE-country').val() == 'USA';
}"]
i had the similar requirement i solved it using the following code
['discharge_date', 'required', 'whenClient' => function($model) {
return $model->discharged == 1;
}, 'enableClientValidation' => false]
It seems that by default Yii2 will do validation in BOTH Server side and Client side. Check the example in Conditional Validation
part of Yii2 doc:
['state', 'required', 'when' => function ($model) {
return $model->country == 'USA';
}, 'whenClient' => "function (attribute, value) {
return $('#country').val() == 'USA';
}"],
you also need a 'whenClient'
code, or as @Alexandr Bordun said, to disable the client validation by 'enableClientValidation' => false
.