Навык custom-validator
Создание пользовательских ограничений валидации для ресурсов API Platform с помощью ограничений Symfony или правил валидации Laravel.
- Звёзды на GitHub
- 29
- Файлы
- 1
- Последний коммит
- 22 окт. 2026 г.
- Лицензия
- —
- Разрешённые инструменты
- —
Что делает навык custom-validator?
custom-validator — это Agent Skill. Создание пользовательских ограничений валидации для ресурсов API Platform с помощью ограничений Symfony или правил валидации Laravel.
Сводка сгенерирована из SKILL.md навыка.
О skill custom-validator
Этот SKILL позволяет бэкенд-разработчикам реализовывать сложную бизнес-логику для ресурсов API Platform. Он предоставляет необходимые паттерны для внедрения пользовательских ограничений валидации, когда стандартных правил Symfony или Laravel недостаточно для специфических требований. Агенту следует загружать этот SKILL, когда пользователю необходимо обеспечить соблюдение форматов, специфичных для предметной области, проверить уникальность данных или внедрить лимиты по частоте запросов и тарифным планам во время операций записи.
Для проектов на базе Symfony навык демонстрирует, как создавать класс Constraint и соответствующий класс ConstraintValidator для обработки такой логики, как проверка лимитов аккаунта. Он также охватывает ограничения на уровне класса для валидации нескольких полей и валидацию через callback для DTO. Для сред Laravel основной упор делается на использование опции rules внутри атрибута ApiResource, поддерживающей массивы, замыкания или строки с именами классов FormRequest. Это гарантирует, что пользовательские бизнес-правила будут корректно возвращать ответы 422 ConstraintViolationList.
Что агент может делать с ним
- 1Соблюдение лимитов аккаунтов согласно тарифному плануСоздание валидатора, который предотвращает превышение пользователем определенного количества аккаунтов в зависимости от его текущего тарифного плана.
Написано на основе skill SKILL.md. Каждый сценарий использования проверен по цитате из него.
Как установить навык custom-validator
Каждая команда копирует папку навыка в каталог навыков клиента. Перезапустите клиент или начните новую сессию, чтобы загрузить его.Установка навыка custom-validator в Плагин
/plugin marketplace add api-platform/skillset /plugin install api-platform@api-platform-skillset
Установка навыка custom-validator в Claude Code
~/.claude/skills/custom-validator/SKILL.md
$ npx degit api-platform/skillset/skills/custom-validator ~/.claude/skills/custom-validatorУстановка навыка custom-validator в Claude Code (project)
.claude/skills/custom-validator/SKILL.md
$ npx degit api-platform/skillset/skills/custom-validator .claude/skills/custom-validatorУстановка навыка custom-validator в Codex
~/.agents/skills/custom-validator/SKILL.md
$ npx degit api-platform/skillset/skills/custom-validator ~/.agents/skills/custom-validatorУстановка навыка custom-validator в Gemini CLI
~/.gemini/skills/custom-validator/SKILL.md
$ npx degit api-platform/skillset/skills/custom-validator ~/.gemini/skills/custom-validatorУстановка навыка custom-validator в Claude.ai
npx degit api-platform/skillset/skills/custom-validator custom-validator && zip -r custom-validator.zip custom-validator # claude.ai → Customize → Skills → + → Create skill → Upload a skill → custom-validator.zip
SKILL.md
Открыть на GitHubCustom Validation Constraints
Create custom validators when built-in Symfony constraints are insufficient.
Constraint Class
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class IsValidAccountLimit extends Constraint
{
public string $message = 'Account limit reached for your current plan.';
public int $limit = 50;
}
Validator Class
Convention: {ConstraintName}Validator in the same namespace.
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class IsValidAccountLimitValidator extends ConstraintValidator
{
public function __construct(
private readonly UserHelper $userHelper,
private readonly AccountRepository $accountRepository,
) {}
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof IsValidAccountLimit) {
throw new \InvalidArgumentException('Unexpected constraint type');
}
if (null === $value || '' === $value) {
return;
}
$user = $this->userHelper->getUser();
$count = $this->accountRepository->countByUser($user->getId());
if ($count >= $constraint->limit) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}
Usage on Properties
use App\Validator\IsValidAccountLimit;
use Symfony\Component\Validator\Constraints as Assert;
class Account
{
#[Assert\NotBlank(groups: ['account:write'])]
#[Assert\Email(groups: ['account:write'])]
#[IsValidAccountLimit(groups: ['account:write'])]
public ?string $address;
}
Class-Level Constraint (UniqueEntity)
For constraints that validate across multiple fields:
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class MongoDBUnique extends Constraint
{
public array $fields = [];
public string $message = 'This value is already used.';
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
Usage:
#[MongoDBUnique(fields: ['address'], groups: ['account:write', 'account:patch'])]
class Account {}
Validation Groups with Operations
Target a constraint to specific operations by passing groups: (as shown above)
and wiring those groups into each operation's validationContext — see
operations for the full per-operation setup.
Callback Validation
For quick one-off validation on DTOs:
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class SendMessage
{
public ?string $text = null;
public ?string $html = null;
#[Assert\Callback]
public function validateContent(ExecutionContextInterface $context): void
{
if (null === $this->text && null === $this->html) {
$context->buildViolation('Either text or html content is required.')
->atPath('text')
->addViolation();
}
}
}
Laravel
Laravel does not use Symfony Constraints/ConstraintValidator. Validation is
declared with Laravel validation rules via the
rules option on #[ApiResource] or per-operation (rules can be an array, a closure,
or a FormRequest class-string). The ValidateProvider runs them before the
processor and emits the same 422 ConstraintViolationList shape.
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Post;
#[ApiResource(rules: ['title' => 'required|min:2'])]
#[Post(rules: ['isbn' => ['required', 'string']])] // per-operation override
class Book extends Model {}
For business rules beyond built-in rules, write a Laravel custom rule (a class
implementing Illuminate\Contracts\Validation\ValidationRule, scaffold with
php artisan make:rule) or a closure rule, and reference it in rules. A
FormRequest class-string is also accepted — its authorize()/rules() run, and an
AuthorizationException maps to 403, ValidationException to 422. Validation groups
and Symfony validationContext do not apply on Laravel; scope rules per operation
instead. Partial PATCH can relax required to sometimes via
partial_patch_validation in config/api-platform.php.
Файлы в этом навыке
1Вопросы о навыке custom-validator
Как установить навык custom-validator в Claude Code?
Выполните npx degit api-platform/skillset/skills/custom-validator ~/.claude/skills/custom-validator. Claude Code загружает навыки из ~/.claude/skills (все проекты) или .claude/skills (один проект) и использует навык, когда его описание соответствует задаче.
Какие клиенты могут использовать навык custom-validator?
Любой клиент, который читает формат Agent Skills: Claude Code, Codex, Gemini CLI и claude.ai (загрузить как ZIP). Скрипты в навыке выполняются только там, где клиент разрешает выполнение кода.
Как создать пользовательский валидатор в Symfony для API Platform?
Вам необходимо создать класс Constraint и соответствующий класс Validator, следуя соглашению об именовании {ConstraintName}Validator в том же пространстве имен.