I have a Symfony validation constraint that removes all Twig tags with a regex before counting the number of characters and validating against the character length limit. (My form allows people to enter a limited subset of Twig tags into a field.) So it does the following:
$parsedLength = mb_strlen( preg_replace('/{%[^%]*%}/', '', $stringValue) );
...If the $parsedLength
value is too long, a build violation occurs.
This works, but it doesn't work for me. Is there a way to pass some kind of service into my validation class and then use that service to render the text without the Twig tags? This seems to be a more harmonious way of doing things than using regular expressions.
Can you share your code? From what I understand, you are applying validation logic inside constraints, but this should go inside the validator.
The correct steps to achieve the desired results are:
one example:
Official documentation: https://symfony.com/doc/current/validation/ custom_constraint.html
I'm not 100% sure this is what you're asking for, but you can create a template based on your input and then render it. Of course remove all the branches, although I'm not sure you always know what the variables are.
I checked and all the examples look very old and I'm not sure if things still work. I can't even find an example in the documentation, although I'm sure it's there somewhere. anyway:
If nothing else, this also lets you verify the actual template. But as already mentioned, I'm not quite sure what
parsed length
means. Anyway, createTemplate is (to me) an interesting method.