3

I'm using Symfony2's tree builder, which I see has some basic validation rules as described here: http://symfony.com/doc/current/components/config/definition.html#validation-rules

Is there a way to also validate by regular expression?

Here's how I'm doing it at the moment, but I am not sure if this is 'best practice'. The config item I want to validate is root_node.

config.yml

my_bundle:
    root_node: /some/path    # this one is valid

Configuration.php

$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('my_bundle');

$rootNode
    ->children()
        ->scalarNode('root_node')
             ->end()
        ->end()
    ->end();

return $treeBuilder;

MyBundleExtension.php

$nodePattern = '#/\w+(/w+)*#';
if (! preg_match($nodePattern, $config['root_node'])) {
    throw new \Exception("root_node is not valid: must match the pattern: $nodePattern");
}

So, what I'm really after is a TreeBuilder method:

->validate()->ifNotMatchesRegex()->thenInvalid()

or, failing that, the best approach to enforce my validation rule.

1 Answer 1

5

What you can do is use the ifTrue method with your custom function. Something like this:

$rootNode
    ->children()
        ->scalarNode('root_node')
            ->validate()
            ->ifTrue(function ($s) {
                return preg_match('#/\w+(/\w+)*#', $s) !== 1;
            })
                ->thenInvalid('Invalid path')
            ->end()
       ->end()
   ->end();

Note the slight modification I made to your regex.

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

2 Comments

Thanks, couldn't have hoped for a better answer. Also in the regex I missed off the ^ and $ markers, so the final version is: #^/\w+(/\w+)*$#
If you want to use custom invalid/error messages, then it might be useful to know that you can include the potentially wrong value in the message like this 'Invalid path : %s'

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.