Custom Rules
Implement Antares\Validation\Attributes\ValidationAttribute to create a custom rule:
use Antares\Validation\Attributes\ValidationAttribute;use Attribute;
#[Attribute(Attribute::TARGET_PARAMETER)]final class Slug implements ValidationAttribute{ public function validate(mixed $value): ?string { if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', (string) $value)) { return 'Must be a valid slug.'; }
return null; }}Return a string error message if validation fails, null if it passes. The rule receives the property’s value after hydration, so it may be null for nullable fields. The built-in rules return null (pass) for values they don’t apply to, and leave “is this required?” to the type or #[NotNull]; doing the same in your own rules keeps them combinable.
Then use it like any built-in attribute:
#[Dto]readonly class CreatePostRequest{ public function __construct( #[NotBlank] public string $title,
#[NotBlank] #[Slug] public string $slug, ) {}}Parameterised Rules
Section titled “Parameterised Rules”Custom attributes can accept constructor arguments:
#[Attribute(Attribute::TARGET_PARAMETER)]final class StartsWith implements ValidationAttribute{ public function __construct(private readonly string $prefix) {}
public function validate(mixed $value): ?string { if (!str_starts_with((string) $value, $this->prefix)) { return "Must start with \"{$this->prefix}\"."; }
return null; }}#[StartsWith('SKU-')]public string $sku,