diff --git a/system/BaseModel.php b/system/BaseModel.php index 227b54b4b15f..a51ae1efbbe6 100644 --- a/system/BaseModel.php +++ b/system/BaseModel.php @@ -199,7 +199,7 @@ abstract class BaseModel /** * Our validator instance. * - * @var ValidationInterface + * @var ValidationInterface|null */ protected $validation; @@ -326,10 +326,6 @@ public function __construct(?ValidationInterface $validation = null) $this->tempUseSoftDeletes = $this->useSoftDeletes; $this->tempAllowCallbacks = $this->allowCallbacks; - /** - * @var ValidationInterface|null $validation - */ - $validation ??= Services::validation(null, false); $this->validation = $validation; $this->initialize(); @@ -1153,6 +1149,10 @@ public function replace(?array $data = null, bool $returnSQL = false) */ public function errors(bool $forceDB = false) { + if ($this->validation === null) { + return $this->doErrors(); + } + // Do we have validation errors? if (! $forceDB && ! $this->skipValidation && ($errors = $this->validation->getErrors())) { return $errors; @@ -1421,6 +1421,8 @@ public function setValidationRule(string $field, $fieldRules) // ValidationRules can be either a string, which is the group name, // or an array of rules. if (is_string($rules)) { + $this->ensureValidation(); + [$rules, $customErrors] = $this->validation->loadRuleGroup($rules); $this->validationRules = $rules; @@ -1455,9 +1457,13 @@ public function cleanRules(bool $choice = false) */ public function validate($data): bool { + if ($this->skipValidation || empty($data)) { + return true; + } + $rules = $this->getValidationRules(); - if ($this->skipValidation || empty($rules) || empty($data)) { + if (empty($rules)) { return true; } @@ -1474,6 +1480,8 @@ public function validate($data): bool return true; } + $this->ensureValidation(); + $this->validation->reset()->setRules($rules, $this->validationMessages); return $this->validation->run($data, null, $this->DBGroup); @@ -1492,6 +1500,8 @@ public function getValidationRules(array $options = []): array // ValidationRules can be either a string, which is the group name, // or an array of rules. if (is_string($rules)) { + $this->ensureValidation(); + [$rules, $customErrors] = $this->validation->loadRuleGroup($rules); $this->validationMessages += $customErrors; @@ -1506,6 +1516,13 @@ public function getValidationRules(array $options = []): array return $rules; } + protected function ensureValidation(): void + { + if ($this->validation === null) { + $this->validation = Services::validation(null, false); + } + } + /** * Returns the model's validation messages, so they * can be used elsewhere, if needed.