symfony 表单验证在使用正则表达式验证之前使用正则表达式清理
我正在使用 Symfony 1.4,并且在表单验证方面有点困难。我有一个如下所示的验证器:
$this->setValidator('mobile_number', new sfValidatorAnd(array(
new sfValidatorString(array('max_length' => 13)),
new sfValidatorRegex(array('pattern' => '/^07\d{9}$/'),
array('invalid' => 'Invalid mobile number.')),
)
));
这是一个用于匹配英国手机号码的简单正则表达式。
然而我的问题是,如果有人提交了这样的字符串:“07 90 44 65 48 1”,正则表达式将失败,但如果首先清理字符串以删除空格,他们会给出有效的数字。
我的问题是我不知道在 symfony 表单框架中的哪个位置可以完成此任务。
我需要从用户输入中删除除数字之外的所有内容,然后使用我的 mobile_number 验证器。
任何想法将不胜感激。谢谢。
I'm using Symfony 1.4 and am a little stuck regarding form validation. I have a validator like the one below:
$this->setValidator('mobile_number', new sfValidatorAnd(array(
new sfValidatorString(array('max_length' => 13)),
new sfValidatorRegex(array('pattern' => '/^07\d{9}$/'),
array('invalid' => 'Invalid mobile number.')),
)
));
That is a simple regex for matching a UK mobile phone number.
However my problem is that if someone submitted a string like this: "07 90 44 65 48 1" the regex would fail but they have given a valid number if a the string was cleaned to remove whitespace first.
My problem is that I don't know where within the symfony form framework I would accomplish this.
I need to strip everything but numbers from the user input and then use my mobile_number validator.
Any ideas would be greatly appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用标准验证器的组合来完成此操作,但构建您自己的自定义验证器可能是最简单的。 symfony 网站上有一个指南: http://www.symfony-project.org/more-with-symfony/1_4/en/05-Custom-Widgets-and-Validators#chapter_05_building_a_simple_widget_and_validator
我认为它应该看起来像这样的内容:
将其保存为 lib/validator/sfValidatorMobilePhone.class.php。然后你可以将其称为
You may be able to do this with a combination of standard validators, but it might well be easiest to construct your own custom validator. There is a guide to this on the symfony website: http://www.symfony-project.org/more-with-symfony/1_4/en/05-Custom-Widgets-and-Validators#chapter_05_building_a_simple_widget_and_validator
I think it should probably look something like this:
Save this as lib/validator/sfValidatorMobilePhone.class.php. You could then call it as
我不了解 Symfony,所以我不知道你会如何清理输入。如果您可以以某种方式进行基于正则表达式的搜索和替换,则可以搜索
/\D+/
并将其替换为任何内容 - 这将从字符串中删除除数字之外的所有内容。小心,它还会删除可能相关的前导+
(?)。如果您无法在验证之前执行“清理步骤”,您可以尝试像这样验证它:
这将匹配包含恰好 11 个数字(以及任意多个非数字字符)的任何字符串,其中前两个需要是
07
。I don't know Symfony, so I don't know how you would go about cleaning the input. If you can do a regex-based search-and-replace somehow, you can search for
/\D+/
and replace that with nothing - this will remove everything except digits from your string. Careful, it would also remove a leading+
which might be relevant (?).If you can't do a "cleaning step" before the validation, you could try validating it like this:
This will match any string that contains exactly 11 numbers (and arbitrarily many non-number characters), the first two of which need to be
07
.