简体   繁体   English

表单验证-组或条件

[英]Form validation - group OR condition

I have form with three element - name, login and email. 我的表格包含三个元素-名称,登录名和电子邮件。 In validation.yml I have: validation.yml我有:

Mark\UserBundle\Entity\User:
    properties:
        name:
            - NotBlank: ~
        login:
            - NotBlank: ~
        email:
            - Email: ~
            - NotBlank: ~

It works, this makes name and login required. 它可以工作,这需要namelogin name Instead, I need name or login required. 相反,我需要namelogin name email remains always required. email始终是必需的。

In Symfony 1.4 I can use sfValidatorOr . 在Symfony 1.4中,我可以使用sfValidatorOr How can I make it in Symfony 2? 如何在Symfony 2中制作它?

I think you should solve this by using the Callback constraint instead: 我认为您应该通过使用Callback约束来解决此问题:

// ...
use Symfony\Component\Validator\ExecutionContextInterface;

class User
{
    // ...

    public function hasCorrectCreditials(ExecutionContextInterface $context)
    {
        $isBlank = function ($val) {
            return null === $this->name || '' === $this->name;
        };

        if ($isBlank($this->name)) {
            if ($isBlank($this->login)) {
                $context->addViolationAdd('login', 'Either name or login should not be blank');
            }
        }
    }
}
Mark\UserBundle\Entity\User:
    constraints:
        - Callback: { methods: [hasCorrectCreditials] }
    properties:
        email:
            - Email: ~
            - NotBlank: ~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM