2013-06-11 54 views
1

如何在All約束內有Optional約束。Symfony驗證可選所有約束

基本上我想驗證一個鍵存在於一個數組中,它的值是一個可以包含空格或任何值的數組。

如果我忽略在Collection約束的關鍵我得到的錯誤:

This field was not expected 

我知道我可以使用allowExtraFields,但我想,以驗證鍵存在。

我雖然我將要使用:

$optional = new Constraints\Optional(); 
$all = new Constraints\All($optional); 

但是,其結果是:

Fatal error: Class 
'Symfony\Component\Validator\Constraints\OptionalValidator' 
not found in 
~\symfony\validator\Symfony\Component\Validator\ConstraintValidatorFactory.php 
on line 36 

下面是完整的代碼:

use Symfony\Component\Validator\Validation; 
use Symfony\Component\Validator\Constraints; 
$input = [ 
    'frames' => [ 
     'header' => [ 
      'test-header-1', 
      'test-header-2', 
      '', 
     ], 
     'content' => [ 
      'test-content-1', 
      'test-content-2', 
      '', 
     ], 
    ], 
]; 
$optional = new Constraints\Optional(); 
$constraint = new Constraints\Collection([ 
    'frames' => new Constraints\Collection([ 
     'header' => new Constraints\All($optional), 
     'content' => new Constraints\All($optional), 
    ]), 
]); 
$validator = Validation::createValidator(); 
$violations = $validator->validateValue($input, $constraint); 
echo $violations; 

我也試過:

$optional = new Constraints\Optional([ 
    new Constraints\Type('array'), 
]); 
$constraint = new Constraints\Collection([ 
    'frames' => new Constraints\Collection([ 
     'header' => $optional, 
     'content' => $optional, 
    ]), 
]); 

但是,那不能驗證密鑰是否存在。

回答

0

只是驗證了headercontent項是數組:

$constraint = new Constraints\Collection([ 
    'frames' => new Constraints\Collection([ 
     'header' => new Constraints\Type('array'), 
     'content' => new Constraints\Type('array'), 
    ]), 
]);