2015-10-01 86 views
0

我想驗證一個數組使用驗證組,因爲一些條件,但驗證組似乎不影響數組?Symfony2數組驗證組

$params = [ 
    'type' => 'a', 
    'province' => 'b', 
    'district' => 'c' 
]; 

$constraints = new Collection([ 
    'type' => [new NotBlank()], 

    'province' => [new NotBlank(['groups' => ['selection']])], 
    'district' => [new NotBlank(['groups' => ['selection']])], 

    'distance' => [new NotBlank(['groups' => ['location']])], 
    'lat' => [new NotBlank(['groups' => ['location']])], 
    'lon' => [new NotBlank(['groups' => ['location']])], 
]); 

$errors = $this->container->get('validator')->validate($params, $constraints, ['selection']); 

驗證錯誤:

Array[distance]: 
This field is missing. (code 1) 
Array[lat]: 
This field is missing. (code 1) 
Array[lon]: 
This field is missing. (code 1) 

感謝您的幫助!

回答

2

您需要使用'allowMissingFields' => true,這樣的:如果約束NotBlank驗證之前就存在領域

$constraints = new Collection(
'allowMissingFields' => true, 
'fields' => [ 
    'type' => [new NotBlank()], 

    'province' => [new NotBlank(['groups' => ['selection']])], 
    'district' => [new NotBlank(['groups' => ['selection']])], 

    'distance' => [new NotBlank(['groups' => ['location']])], 
    'lat' => [new NotBlank(['groups' => ['location']])], 
    'lon' => [new NotBlank(['groups' => ['location']])], 
]); 

https://symfony.com/doc/2.7/reference/constraints/Collection.html

的CollectionValidator正在檢查。