Sometimes, after model is saved, the rules changes then it makes a bad validation on client side, because javascript is rendered using the old values, currently not exists a easy way to refresh the validators after are created, because yii\base\Model::$_validators is private, then I suggest make yii\base\Model::$_validators protected or implement in yii\base\Model the next function
public function refreshValidators() {
$this->_validators = $this->createValidators();
}
In Yii 2, the client side validation is enabled by default. But there are many cases you have to turn it off manually (per form or per field) and use the ajax validation instead because of the problem you have described.
Unfortunately this won’t solve the problem, because a change on the server side will not be reflected automatically in the javascript on the client. Also we seldom need to modify the validation code after it was created. Note that the life cycle of the code on the server side is per request.
Try disable the client side validation and use ajax validation instead.
Today I had similar question. How to refresh _validators after method $model->load() is called.
Why? … I am using calculated validation rules. Namely: list of the “required” fields is dynamical and is based on other values. For example on column “status” (which is changed by the user in the edit-form).
How method load() works:
It loads the record from DB. This record contains old values.
Validation rules are calculated. In my case list of “required” columns is calculated based on the old DB values
Validation rules are saved to private property _validators
Then data from POST is assigned to the model
Later, when I call save(), previously calculated validation rules are applied, but they are wrong, because “required” columns were calculated using the old values that are in DB, not using the new values that were entered by the user in the form.
I think the only way how to delete _validators and force method createValidators() to be called again is to use “clone” command. See method __clone in the yii\base\Model. Example:
if ($this->request->isPost && $model->load($this->request->post())) {
$model = clone $model;
if ($model->save()){
// ...
}
}