2

For each user I have name, surname and phone numbers. I need to validate these fields in my validation.yml to check if they are not empty. For name and surname validation I have this and it is working very well:

RFQ\IronilBundle\Entity\User:
properties:
    name:
        - NotBlank: { groups: [not_empty] }
    surname:
        - NotBlank: { groups: [not_empty] }

Problem is there that I can't to find any example in documentation how to validate phone field, because each user can have more than one phone number. My entity for phone is:

/**
 * @ORM\Column(type="array", nullable=true)
 * @Assert\NotNull()
 */
protected $phone;

and upon registering I insert in database empty array value (I need this to show empty phone field in my edit action):

public function __construct() {
    parent::__construct();
    $this->phone = array('');
}

Thank you!

2
  • 2
    I think the All validator do this job for you. Theck the doc Commented Sep 25, 2014 at 16:03
  • 2
    You could always use a Callback validator that would call an entity method that does the checks. Commented Sep 25, 2014 at 16:07

1 Answer 1

2

There's an All validation type that will iterate over arrays and Traversable objects and apply constraints to them. So for example, if you want to make sure each phone element is max 10 characters, you could do the following:

RFQ\IronilBundle\Entity\User:
properties:
    name:
        - NotBlank: { groups: [not_empty] }
    surname:
        - NotBlank: { groups: [not_empty] }
    phone:
        - All:
            - NotBlank:  ~
            - Length:
                max: 10

The reference documentation.

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for answer! But I need to assign a group to this validation too. Maybe you know how I can do that?
- All: { groups: [not_empty] } throws me syntax error, but - NotBlank: { groups: [not_empty] } just doesn't work.
I think I remember having this conversation with someone else too. What was the error, that the All constraint doesn't support groups?
Unable to parse at line 9 (near " - NotBlank: ~").
Ah invalid yml syntax. So add - groups: [not_empty] as an element of All like the other properties (so just above - NotBlank: ~).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.