-
Notifications
You must be signed in to change notification settings - Fork 11.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.7] an array of messages for custom validation rules #26327
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you fix the StyleCI failures?
Should be fixed now! |
@@ -16,7 +16,7 @@ public function passes($attribute, $value); | |||
/** | |||
* Get the validation error message. | |||
* | |||
* @return string | |||
* @return string|array |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you also update the phpdoc of the implementations?
How about being able to return |
Also: I think you should keep in mind that the field where the error is shown. Right now multiple errors are shown on the parent field: foreach ($messages as $message) {
$this->messages->add($attribute, $this->makeReplacements(
$message, $attribute, get_class($rule), []
));
} While I expected it to be more like: foreach ($messages as $childAttribute => $message) {
$nestedAttribute = "{$attribute}.{$childAttribute}";
$this->messages->add($nestedAttribute, $this->makeReplacements(
$message, $nestedAttribute, get_class($rule), []
));
} |
@brendt Interesting. Why would it make assumptions about a child attribute? I'm not sure I would expect that behavior. |
@taylorotwell let's assume the following example, it's nothing I'd do IRL, but it illustrates my point. // The rules in the request class
$rules = [
'articles' => new ArticleRule(),
]; // ArticleRule will validate two properties: type and amount
public function passes($attribute, $value)
{
if (!in_array($value['type'], ArticleType::toArray())) {
$this->messages['type'] = 'The article type must be defined in the ArticleType enum.';
}
if ($value['amount'] < 0) {
$this->messages['amount'] = 'You can only specify a positive amount.';
}
return empty($this->messages);
} Say both rules fail, we'd get two errors in the final result, mapping to the |
At a current project we're working on we have a lot(+200) rules for validating a request. The solution is splitting these rules into separate custom rule classes. Like so
Then in our UnitArticlesRule class we do the following:
As you can see, multiple articles can have validation errors. In the current implementations of custom validation rules we can only return a string. This PR adds the ability to return an array of messages so the example above will work.
The PR won't break any functionality and two tests are added.