Symfony Validator集合约束不适用于组

时间:2019-02-13 13:19:55

标签: php symfony symfony4 symfony-validator

我已经尝试验证输入数组。 该数组必须根据不同的条件进行验证,存在一个约束type,该约束必须在每个请求上都满足,然后在其他请求(googlecredentialsfacebook)上都必须满足取决于请求值。

所以我的约束如下:

/* ... */
$this->validator = Validation::createValidator();

$this->rules = [
    "type" => new Assert\Choice([
        "choices" => ["credentials", "facebook", "google"],
        "message" => "Invalid type '{{ value }}'. Must be one of: credentials, facebook or google",
        "min" => 1,
        "max" => 1
    ]),
    "username" => [
        new Assert\NotBlank([]),
        new Assert\Regex([
            "pattern" => "/^[\w0-9\ ]+$/i",
            "message" => "Username can only consist of alphanumeric characters, spaces, _, ., -"
        ])
    ],
    "token" => new Assert\NotBlank([]),
    "password" => [
        new Assert\NotBlank([]),
        new Assert\Length([
            "min" => 6,
            "minMessage" => "Password must be at least 6 characters long",
        ]),
    ],
    "passwordConfirm" => [
        new Assert\NotBlank([]),
        new Assert\IdenticalTo([
            "propertyPath" => "password",
        ])
    ]
];

$this->constraints = [
    new Assert\Collection([
        "groups" => ["Default", "type"],
        "fields" => [
            "type" => $this->rules["type"]
        ]
    ]),
    new Assert\Collection([
        "groups" => ["Default", "facebook", "google", "credentials"],
        "fields" => [
            "username" => $this->rules["username"]
        ]
    ]),
    new Assert\Collection([
        "groups" => ["Default", "facebook", "google"],
        "fields" => [
            "token" => $this->rules["token"]
        ]
    ]),
    new Assert\Collection([
        "groups" => ["Default", "credentials"],
        "fields" => [
            "password" => $this->rules["password"],
            "passwordConfirm" => $this->rules["passwordConfirm"]
        ]
    ]),
];

$this->validator->validate($data, $this->constraints, ["type", $data["type"] ?? "null"]);

/* ... */

给出以下数据:

$data = [
  "type" => "credentials"
];

会给我错误:

{
    "username": "This field is missing.",
    "type": "This field was not expected.",
    "password": "This field is missing.",
    "passwordConfirm": "This field is missing."
}

不应出现未预期的类型。 我开始为根使用Assert\Collection而不是数组(例如标量值的示例),但这也没有用。

我已经搜索了完整的文档,但找不到解决方案或有关如何使用组的更详细说明。

0 个答案:

没有答案