Skip to content

feat: add ability to specify a custom message for validation rules #1611

@azjezz

Description

@azjezz

Description

When adding rule validation to a DTO, i would like to be able to specify a custom message.

Example:

use Tempest\Validation\Rules;

final class Book {
    #[Rules\HasLength(
      min: 5,
      minMessage: 'book title is too short.',
      max: 50,
      maxMessage: 'book title is too long!',
    )]
    public string $title;

    #[Rules\IsNotEmptyString(message: 'book description should not be empty!')]
    public string $description;

    #[Rules\HasDateTimeFormat('Y-m-d', 'book publish date is incorrectly formatted!')]
    public ?DateTime $publishedAt = null;
}

It would also be nice to be able to specify translation keys instead, allowing users to translate validation error messages depending on the request locale.

use Tempest\Validation\Rules;

final class Book {
    #[Rules\HasLength(
      min: 5,
      minMessage: 'book.error.title.short',
      max: 50,
      maxMessage: 'book.error.title.long',
    )]
    public string $title;

    #[Rules\IsNotEmptyString(message: 'book.error.description.empty')]
    public string $description;

    #[Rules\HasDateTimeFormat('Y-m-d', 'book.error.published_at.format')]
    public ?DateTime $publishedAt = null;
}

Benefits

More customization, and better / more specific error messages to end users.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions