I tried creating custom validation rule to use when building form following: example.
Here's what I'v came to:
namespace Path\ToBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class NotValidSearch extends Constraint
{
public $message = 'Search string is invalid format.';
}
namespace Salda\ClientControlBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ContainsNotValidSearchValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (count(explode(' ', $value)) !== 3) {
$this->context->addViolation($constraint->message);
}
}
}
and then tried using it inside form builder class:
use Path\ToBundle\Validator\Constraints\NotValidSearch;
$builder->add('search', 'search', array(
'label' => 'Predecessor',
'required' => false,
'mapped' => false,
'constraints' => new NotValidSearch(array(
'message' => 'invalid message ph'
))
));
But when I am submiting the form it throws error: Fatal error: Class 'Path\ToBundle\Validator\Constraints\NotValidSearchValidator' not found in /path/to/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Validator/ConstraintValidatorFactory.php on line 71
My question is: have I misunderstood how to use custom validators or I am just missing something or doing it wrong? Because I wan't to use it in when building the form since I need to use it on non mapped property. And is this an appropriate way of doing this?, or maybe there's other way?