Skip to content

Commit

Permalink
[9.x] Make password rule errors translatable
Browse files Browse the repository at this point in the history
  • Loading branch information
reziamini committed Apr 20, 2022
1 parent 0805622 commit 57ce1b2
Showing 1 changed file with 39 additions and 7 deletions.
46 changes: 39 additions & 7 deletions src/Illuminate/Validation/Rules/Password.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')
);
}
});

Expand All @@ -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;
Expand Down Expand Up @@ -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];
}
}

0 comments on commit 57ce1b2

Please sign in to comment.