Symfony验证单个属性

时间:2018-07-23 20:15:09

标签: validation symfony-3.3

symfony验证程序可以验证深度嵌套对象的单个属性,例如;

$ this-> validator-> validateProperty($ object,'person.addressHistory [2] .town');

1 个答案:

答案 0 :(得分:0)

看起来还不可能。但是,您可以使用属性访问器来获取值并将其传递给验证器。

我已经测试过

Author.php

/**
 * @Assert\NotBlank()
 * @Assert\Length(min="10", max="255")
 */
private $firstname;

Controller.php

<?php

namespace App\Controller;

use App\Entity\Author;
use App\Entity\Book;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * @Route("/validator")
 */
class ValidatorController extends Controller
{
    /**
     * @var ValidatorInterface
     */
    private $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    /**
     * @Route(name="app_validator_index", path="/")
     */
    public function index()
    {
        $author = new Author();
        $author->setFirstname('too short');
        $book = new Book();
        $book->setAuthor($author);

        $pa = new PropertyAccessor();

        dump($this->validator->validateProperty($author, 'firstname')); // invalid
        dump($this->validator->validateProperty($book, 'author.firstname')); // valid
        dump($this->validator->validate($pa->getValue($book, 'author'))); // invalid
        dump($this->validator->validateProperty($pa->getValue($book, 'author'), 'firstname')); // invalid

    }
}