簡體   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