Doctrine约束:是用JavaScript实现的自定义验证器吗?

时间:2013-02-27 07:52:26

标签: forms symfony validation

我在文件src/HQF/Bundle/PizzasBundle/Form/Type/VilleType.php

中创建了自己的Form类

它真的很短:

<?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)
            );  
        }   
    }   
}

这只是一个简单的Regexp。当我在表单中说array('max_length' => 5)时,在客户端添加了一些JavaScript验证。这很好。有没有办法添加自定义验证器,所以它们也在客户端添加。我想像array('max_length' => 5, 'FrenchPostalCode')或其他什么?

1 个答案:

答案 0 :(得分:1)

Symfony2中没有内置的JavaScript验证。您所谈论的是HTML5 form validation,它直接由浏览器支持 - 不涉及JavaScript。

您可以尝试使用pattern attribute来实现所需的验证。如果它没有解决问题,你将不得不使用JavaScript。