【发布时间】:2014-04-11 19:59:16
【问题描述】:
我正在尝试添加 Symfony 2.1 表单验证,以确保提交的生日在 1900 年 1 月 1 日或之后。
我希望以下日期通过验证:
- 01/01/1900
- 1999 年 12 月 20 日
- 08/20/2002
我希望以下日期验证失败:
- 12/20/1899
- 08/08/0971
我尝试在validation.yml 中使用正则表达式:
// src/Company/UsersBundle/Resources/config/validation.yml
dateOfBirth:
- NotBlank: { groups: [verifyGenderAndAge] }
- Date:
message: "This is not a valid date. Please enter your date of birth in the following format, MM/DD/YYYY."
groups: [verifyGenderAndAge]
- Regex:
pattern: "/\d{1,2}\/\d{1,2}\/(19|20)\d{2}/"
message: This is not a valid date. Please enter your date of birth after 01/01/1900 in the following format, MM/DD/YYYY.
我使用这个验证器得到的错误是:
关键 - Symfony\Component\Validator\Exception\UnexpectedTypeException: 字符串类型的预期参数,给定对象(未捕获的异常) /Users/user/code/base/api/vendor/symfony/symfony/src/Symfony/Component/Validator/Constraints/RegexValidator.php 第 38 行
我尝试过创建自定义验证器:
约束:
// src/Company/UsersBundle/Validator/Constraints/IsValidBirthdate.php
namespace Company\UsersBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class IsValidBirthdate extends Constraint
{
/**
* @Annotation
*/
public $message = "This is not a valid date. Please enter your date of birth after 01/01/1900 in the following format, MM/DD/YYYY.";
}
验证器:
// src/Company/UsersBundle/Validator/Constraints/IsValidBirthdateValidator.php
namespace Company\UsersBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class IsValidBirthdateValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (get_class($value) != 'DateTime' || !preg_match('/\d{1,2}\/\d{1,2}\/(19|20)\d{2}/', $value->format('m/d/Y'), $matches)) {
$this->context->addViolation(
$constraint->message,
array('%string%' => $value)
);
}
}
}
实体 YAML 文件:
// src/Company/UsersBundle/Resources/config/validation.yml
...
dateOfBirth:
- NotBlank: { groups: [verifyGenderAndAge] }
- Date:
message: "This is not a valid date. Please enter your date of birth in the following format, MM/DD/YYYY."
groups: [verifyGenderAndAge]
- Company\UsersBundle\Validator\Constraints\IsValidBirthdate: ~
...
使用自定义验证器时出错:
在渲染模板期间引发了异常 (“可捕获的致命错误:DateTime 类的对象不能 转换为字符串 /Users/user/code/Company/api/vendor/symfony/symfony/src/Symfony/Component/Translation/IdentityTranslator.php 第 62 行") 在第 276 行的 form_div_layout.html.twig 中。
500 内部服务器错误 - Twig_Error_Runtime
关于如何在 Symfony 2.1 中实现这个验证器有什么想法吗?
【问题讨论】:
-
我实际上并没有验证日期本身,只是检查日期的年份,我已经有标准 Symonfy 2 日期验证器
-
您是否使用与实体链接的表单?还是没有要形成的链接实体?
-
有一个实体链接到表单
标签: php regex validation symfony datetime