duanhui9840 2012-12-11 15:19
浏览 54
已采纳

在Symfony2配置TreeBuilder中使用正则表达式验证?

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条回答 默认 最新

  • doufei0933 2012-12-11 16:03
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试