繁体   English   中英

Symfony2-正则表达式验证

[英]Symfony2 - Regex validation

我需要创建一个字段,该字段作为选项获取正则表达式字符串。

所以,我做了PatternType字段:

public function getDefaultOptions(array $options)
{

    $defaultOptions = array(
        'data'              => null,
        'data_class'        => null,
        'trim'              => true,
        'required'          => true,
        'read_only'         => false,
        'max_length'        => null,
        'pattern'           => null,
        'property_path'     => null,
        'by_reference'      => true,
        'error_bubbling'    => false,
        'regexp'            => false,
        'error_mapping'     => array(),
        'label'             => null,
        'attr'              => array(),
        'invalid_message'   => 'This value is not valid',
        'invalid_message_parameters' => array()
    );

    $class = isset($options['data_class']) ? $options['data_class'] : null;

    // If no data class is set explicitly and an object is passed as data,
    // use the class of that object as data class
    if (!$class && isset($options['data']) && is_object($options['data'])) {
        $defaultOptions['data_class'] = $class = get_class($options['data']);
    }

    if ($class) {
        $defaultOptions['empty_data'] = function () use ($class) {
            return new $class();
        };
    } else {
        $defaultOptions['empty_data'] = '';
    }


    $patt = $options['regexp'];

    unset($options['regexp']);

    $defaultOptions['validation_constraint'] = new Regex(
                                                      array(
                                                          'pattern' => $patt,
                                                          'match' => true,
                                                          'message' => 'Niewłaściwy format'
                                                           )
                                                        );


    var_dump($defaultOptions);


    return $defaultOptions;
}

var_dump返回格式正确的设置数组,其中包含regex对象-但是在生成表单时,验证不起作用-传递任何值。 知道为什么吗?

你为什么做这个? 已经有一个正则表达式验证器 只需在该验证器中使用普通文本字段即可。

如果您需要一个没有模型类绑定的表单,请阅读相应的部分

好的,我发现了问题所在-您只能将验证器常量添加到根表单对象(其他symfony只需忽略)即可。 因此,似乎我需要的只是获得root形式,在其中添加validator_constant并设置validator_group选项。 然后,只需为字段分配适当的validator_group即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM