dongtan7418 2013-07-11 14:48
浏览 58
已采纳

Symfony2验证 - 如何使用表单中的值?

I have a form where I have to fill in some information. For one of the fields of the form, I need to create a custom validator. In fact, I need to valdiate that the entered string is in a specific format like ab.123.cd

I am able to validate this by using regexp, but the "ab" should be eqal to another field of my form, so I need to access this other field in my validator class.

Here is my validator:

public function validate($value, Constraint $constraint)
{       
    preg_match('/[^\/]+/i', $value, $publisherDoiAbbr);
    if($publisherDoiAbbr[0] !== $enquiry->getPublisher()->getDoiAbbreviation()) {
        $this->context->addViolation($constraint->message_publisher_DOI);
    }
    $this->context->addViolation($constraint->message_journal_DOI);
}

I need here the $enquiry->getPublisher()->getDoiAbbreviation()

Do you know how can I access the values of my form in the validator class?

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • doufenzhu7012 2013-07-11 16:51
    关注

    What you want to do is make a "CLASS CONSTRAINT" validator.

    Scroll down here:

    http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

    until you get to the class constraint section for an example.

    ================================================================

    I don't understand what is te "getTargets()"

    Add this method to your Constraint class (not the validator class)

    class MyConstraint extends Constraint
    {
        public function getTargets()
        {
            return self::CLASS_CONSTRAINT;
        }
    

    Once that has been added then your validator method will receive an object instead of a single value.

    class MyValidator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            // $value will be an object, adjust your code accordingly
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?