ファイルに独自の Form クラスを作成しましたsrc/HQF/Bundle/PizzasBundle/Form/Type/VilleType.php
それは本当に短いです:
<?php
namespace HQF\Bundle\PizzasBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class VilleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cp', 'text', array('max_length' => 5));
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'HQF\Bundle\PizzasBundle\Entity\Ville',
);
}
public function getName()
{
return 'ville';
}
}
これで、ファイルにバリデーターを作成しましたsrc/HQF/Bundle/PizzasBundle/Validator/Constraints/FrenchPostalCodeValidator.php
。それは機能するので、簡潔にするために、バリデータークラスのコードは次のとおりです。
<?php
namespace HQF\Bundle\PizzasBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class FrenchPostalCodeValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!preg_match('/^([0-9]{5}|2[A|B])$/', $value, $matches)) {
$this->context->addViolation(
$constraint->message,
array('%string%' => $value)
);
}
}
}
これは単なる正規表現です。array('max_length' => 5)
フォームで、クライアント側にいくつかの JavaScript 検証が追加されていると言います。これはいいね。クライアント側にも追加されるように、カスタムバリデータを追加する方法はありますか。私は何かのようなものだと思いarray('max_length' => 5, 'FrenchPostalCode')
ますか?