From 57ce1b2232a8c02630bd4051ce248c20d0e29bca Mon Sep 17 00:00:00 2001 From: Reza Amini Date: Wed, 20 Apr 2022 13:20:13 +0430 Subject: [PATCH] [9.x] Make password rule errors translatable --- src/Illuminate/Validation/Rules/Password.php | 46 +++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/src/Illuminate/Validation/Rules/Password.php b/src/Illuminate/Validation/Rules/Password.php index 676dda6f49f3..eecc5d2b20dd 100644 --- a/src/Illuminate/Validation/Rules/Password.php +++ b/src/Illuminate/Validation/Rules/Password.php @@ -303,19 +303,31 @@ public function passes($attribute, $value) $value = (string) $value; if ($this->mixedCase && ! preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/u', $value)) { - $validator->errors()->add($attribute, 'The :attribute must contain at least one uppercase and one lowercase letter.'); + $validator->errors()->add( + $attribute, + $this->getErrorMessage('validation.password.mixedCase') + ); } if ($this->letters && ! preg_match('/\pL/u', $value)) { - $validator->errors()->add($attribute, 'The :attribute must contain at least one letter.'); + $validator->errors()->add( + $attribute, + $this->getErrorMessage('validation.password.letters') + ); } if ($this->symbols && ! preg_match('/\p{Z}|\p{S}|\p{P}/u', $value)) { - $validator->errors()->add($attribute, 'The :attribute must contain at least one symbol.'); + $validator->errors()->add( + $attribute, + $this->getErrorMessage('validation.password.symbols') + ); } if ($this->numbers && ! preg_match('/\pN/u', $value)) { - $validator->errors()->add($attribute, 'The :attribute must contain at least one number.'); + $validator->errors()->add( + $attribute, + $this->getErrorMessage('validation.password.numbers') + ); } }); @@ -327,9 +339,7 @@ public function passes($attribute, $value) 'value' => $value, 'threshold' => $this->compromisedThreshold, ])) { - return $this->fail( - 'The given :attribute has appeared in a data leak. Please choose a different :attribute.' - ); + return $this->fail($this->getErrorMessage('validation.password.uncompromised')); } return true; @@ -361,4 +371,26 @@ protected function fail($messages) return false; } + + /** + * Returns the translated error message + * + * @param string $key + * @return string + */ + protected function getErrorMessage($key){ + $messages = [ + 'validation.password.mixedCase' => 'The :attribute must contain at least one uppercase and one lowercase letter.', + 'validation.password.letters' => 'The :attribute must contain at least one letter.', + 'validation.password.symbols' => 'The :attribute must contain at least one symbol.', + 'validation.password.numbers' => 'The :attribute must contain at least one number.', + 'validation.password.uncompromised' => 'The given :attribute has appeared in a data leak. Please choose a different :attribute.', + ]; + + if (($message = $this->validator->getTranslator()->get($key)) !== $key){ + return $message; + } + + return $messages[$key]; + } }