yiisoft / validator

Yii validator library
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
110 stars 36 forks source link

Include attribute name in error messages when it's present #630

Closed arogachev closed 4 months ago

arogachev commented 8 months ago
Name must contain at least 8 characters.

instead of

This value must contain at least 8 characters.

Suggested by @vjik.

dood- commented 6 months ago

I'll take it

arogachev commented 6 months ago

I had an idea regarding to this issue. We discussed it within the team, but I'm not sure it was conveyed / understood. The suggestion of mine is to not have separate error messages, but instead, reorganize existing ones and make them dynamic.

For example let's take URL rule's error message:

https://github.com/yiisoft/validator/blob/e18482f3908322bcc49b4ae480dca282792e8e9e/src/Rule/Url.php#L83

It can be transformed like this:

{something} is not a valid URL.

{something} is a new placeholder (working title).

If attribute display is set (can be done with a separate setting / flag) and attribute name is "Vendor site", the message becomes:

Vendor site is not a valid URL.

Otherwise:

This value is not a valid URL.

"This value" is the most used definition of a validated value in the current error messages. Can be customizable too.

With this approach some messages can be rephrased without losing the original meaning to avoid translation complexity.

samdark commented 6 months ago

Related to https://github.com/yiisoft/validator/pull/643

dood- commented 6 months ago

I think it is posiiblie to add the "error_message_template" property in the config and use it: 'error_message_template' => 'This value {message}!' or 'error_message_template' => '{attribute} {message}'.

It can be overridden using the attribute:

#[ErrorMessage(template: 'This value {message}')] // Redefine the template for the entire object
final class Dto
{
    #[Required]
    #[Label('First Name')]
    #[ErrorMessage(template: '{attribute} {message}')] // or for a specific property
    public string $name = '';

    #[Number(min: 21)]
    public int $age = 17;
}
vjik commented 6 months ago

I thnik, @arogachev suggest modify current error messages. For example:

The value must be a string.
↓
{attribute} must be a string.

By default message will be "Value must be a string.". If exist label (for example, "Name"), message will be "Name must be string".

@arogachev, is it right?

PS It may to implement in separate PR after https://github.com/yiisoft/validator/pull/643

arogachev commented 5 months ago

@vjik Yes.