1

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?

1 Answer 1

2

In the base Symfony\Component\Validator\Constraint class there is the validatedBy method

public function validatedBy()
{
    return get_class($this).'Validator';
}

Meaning that your class NotValidSearch would be validated by NotValidSearchValidator rather than your chosen ContainsNotValidSearchValidator.

You will either need to change the name of your validator to NotValidSearchValidator or change the validatedBy to the correct name of your validator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.