I have a Symfony validation constraint that removes all Twig tags with regular expressions before counting characters and validating based on character length limits. (My form allows people to enter a limited subset of Twig tags in a field.) So it does something like this:
$parsedLength = mb_strlen(
preg_replace('/{%[^%]*%}/', '', $stringValue)
);
… then builds violations if the $parsedLength
value is too long.
This works, but it doesn’t sit right with me. Is there a way I can pass a service of some sort into my validation class and then use that service to render the text without Twig tags? That seems like it would be the more symfonic way to do things, rather than using regular expressions.
2
Answers
can you share your code please? As i understand, you’re applying the validation logic inside the constraint, but that should go inside a validator.
The right steps to achieve the expected result are:
An example:
Official doc: https://symfony.com/doc/current/validation/custom_constraint.html
I’m not 100% this is what you are asking for but you can create a template from your input and then render it. Certainly get’s rid of all the twig stuff though I am not sure if you always know what the variables will be.
I poked around a bit and all the examples seem quite old and I was not sure if things would still work. Could not even find an example in the docs though I’m sure it is there somewhere. In any event:
If nothing else this allows you to validate the actual template as well. But as already mentioned, I’m not really sure what
parsed length
is supposed to mean. Regardless, createTemplate is an interesting (to me) method.