我在文件中创建了自己的 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')什么?