[英]Symfony2 - Regex validation
I need to create field that as option gets regex string. 我需要创建一个字段,该字段作为选项获取正则表达式字符串。
So, i made PatternType field: 所以,我做了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 returns well formatted settings array, with regex object within - but when form is generated validation doesn't work - pass any value. var_dump返回格式正确的设置数组,其中包含regex对象-但是在生成表单时,验证不起作用-传递任何值。 Any idea why?
知道为什么吗?
Why are you doing this? 你为什么做这个? There is a regex validator already.
已经有一个正则表达式验证器 。 Just use a normal text field with that validator.
只需在该验证器中使用普通文本字段即可。
In case you need a form without a model class to bind to, read the corresponding section . 如果您需要一个没有模型类绑定的表单,请阅读相应的部分 。
Ok, I found what was wrong - you can only add validator constant to root form object (others symfony simply ignore). 好的,我发现了问题所在-您只能将验证器常量添加到根表单对象(其他symfony只需忽略)即可。 So it seems that what I need is simply get root form, add there validator_constant with validator_group option set.
因此,似乎我需要的只是获得root形式,在其中添加validator_constant并设置validator_group选项。 Then just assign field proper validator_group.
然后,只需为字段分配适当的validator_group即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.