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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化