Правило Length
Правило Length используется в формах Symfony для проверки длины значения. Оно гарантирует, что строка содержит определённое количество символов, а коллекция или массив - определённое количество элементов. Правило вешается на поле формы через опцию constraints или используется как атрибут в сущности. Первым параметром можно передать минимальную длину min, максимальную длину max, точное значение exactMessage, либо комбинацию этих ограничений.
Синтаксис
#[Length(
min: 5,
max: 10,
minMessage: '...',
maxMessage: '...',
exactMessage: '...',
charsetMessage: '...',
countUnit: '...',
charset: 'UTF-8',
normalizer: null,
groups: null,
payload: null
)]
Пример
Давайте создадим форму с полем title и повесим на него ограничение длины от 5 до 10 символов:
<?php
namespace AppForm;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsLength;
class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('title', TextType::class, [
'constraints' => [
new Length([
'min' => 5,
'max' => 10,
'minMessage' => 'Title must be at least {{ limit }} characters long',
'maxMessage' => 'Title cannot be longer than {{ limit }} characters',
]),
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
?>
Пример
Давайте проверим валидацию в контроллере. Создадим форму, отправим невалидные данные и выведем ошибки:
<?php
namespace AppController;
use AppFormArticleType;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_form')]
public function index(Request $request): Response
{
$form = $this->createForm(ArticleType::class);
$form->submit(['title' => 'abc']);
if ($form->isValid()) {
return new Response('Valid');
}
$errors = [];
foreach ($form->getErrors(true) as $error) {
$errors[] = $error->getMessage();
}
return new Response(implode(', ', $errors));
}
}
?>
Результат выполнения кода:
"Title must be at least 5 characters long"
Пример
Давайте проверим точную длину строки. Установим ограничение exact равное 5:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyComponentFormFormFactoryInterface;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentValidatorConstraintsLength;
class ArticleController extends AbstractController
{
#[Route('/article/exact', name: 'article_exact')]
public function exact(FormFactoryInterface $factory, Request $request): Response
{
$form = $factory->createBuilder()
->add('title', TextType::class, [
'constraints' => [
new Length([
'exact' => 5,
'exactMessage' => 'Title must be exactly {{ limit }} characters',
]),
],
])
->getForm();
$form->submit(['title' => 'abcde']);
if ($form->isValid()) {
return new Response('Valid');
}
$errors = [];
foreach ($form->getErrors(true) as $error) {
$errors[] = $error->getMessage();
}
return new Response(implode(', ', $errors));
}
}
?>
Результат выполнения кода:
"Valid"