Skip to content

Instantly share code, notes, and snippets.

@viccherubini
Created September 29, 2015 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viccherubini/16679954829940c090bb to your computer and use it in GitHub Desktop.
Save viccherubini/16679954829940c090bb to your computer and use it in GitHub Desktop.
Symfony Validation
<?php
$constraints = [
// Here is the issue, I want to assert the vendor_num key
// of the $vendor array below is both not blank AND has
// a length <= 24 (and who knows, more constraints down the road).
// The issue is that Collection() expects vendor_num to
// be an array. How to do I chain these without calling
// addPropertyConstraint() a bunch because I don't have access to it.
'vendor_num' => new Assert\Collection([
'constraints' => [
new Assert\NotBlank,
new Assert\Length([
'max' => 24
])]
]),
'display_name' => new Assert\Length(['max' => 2]),
'email_address' => new Assert\Email
];
$vendor = [
'vendor_num' => 'THIS IS A VERY LONG VENDOR NUMBER THAT SHOULD FAIL',
'display_name' => 'This should fail',
'email_address' => 'invalid'
];
$constraint = new Assert\Collection($constraints);
$violations = $this->validator
->validateValue($vendor, $constraint);
@weaverryan
Copy link

You're so close!

$constraints = [
    'vendor_num' => array(
        new Assert\NotBlank,
        new Assert\Length([
            'max' => 24
        ])
    ),
    // ...
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment