【问题标题】:Use regex validation in Symfony2 configuration TreeBuilder?在 Symfony2 配置 TreeBuilder 中使用正则表达式验证?
【发布时间】:2012-11-29 03:48:17
【问题描述】:

我正在使用 Symfony2 的树构建器,我看到它有一些基本的验证规则,如下所述:http://symfony.com/doc/current/components/config/definition.html#validation-rules

有没有办法也通过正则表达式进行验证?

这是我目前的做法,但我不确定这是否是“最佳做法”。我要验证的配置项是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");
}

所以,我真正追求的是 TreeBuilder 方法:

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

或者,如果做不到这一点,则执行我的验证规则的最佳方法。

【问题讨论】:

    标签: php symfony configuration


    【解决方案1】:

    您可以将ifTrue 方法与您的自定义函数一起使用。像这样的:

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

    请注意我对您的正则表达式所做的轻微修改。

    【讨论】:

    • 谢谢,希望得到更好的答案。同样在正则表达式中,我错过了 ^ 和 $ 标记,所以最终版本是:#^/\w+(/\w+)*$#
    • 如果您想使用自定义的无效/错误消息,那么知道您可以在消息中包含潜在的错误值可能会很有用,例如“无效路径:%s”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多