我尝试创建我的验证器,但是它不起作用。 文档无济于事,因为它只关心对象验证,并提供了一个数组验证示例。
我正在尝试根据随数据一起发送的字段来验证我的数据。
因此,请求中包含type
,credentials
或google
的字段facebook
,并根据此字段的值来验证其他字段。
当然,type
必须先通过验证。
我尝试遵循集合文档,但只得到了意外的异常和结果。有时会出错,有时会出错,但事情并没有按预期工作。
给出以下示例:
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
require_once(__DIR__ . "/../vendor/autoload.php");
$validator = Validation::createValidator();
$constraints = new Assert\Collection([
"type" => [
new Assert\Required([
"groups" => ["type"],
"constraints" => new Assert\Choice([
"choices" => ["credentials", "facebook", "google"],
])
]),
],
"username" => [
new Assert\NotBlank([
"groups" => ["credentials", "facebook", "google"]
])
],
"password" => [
new Assert\NotBlank([
"groups" => ["credentials"]
]),
new Assert\Length([
"min" => 6,
"groups" => ["credentials"]
]),
],
"passwordConfirm" => [
new Assert\NotBlank([
"groups" => ["credentials"],
]),
new Assert\IdenticalTo([
"groups" => ["credentials"],
"propertyPath" => "password"
])
]
]);
$data = [];
$errors = $validator->validate($data, $constraints, "credentials");
foreach ($errors as $error) {
echo $error->getPropertyPath() . ": " . $error->getMessage() . "<br />";
}
将输出:
[type]: This field is missing.
[username]: This field is missing.
[password]: This field is missing.
[passwordConfirm]: This field is missing.
即使我已将"credentials"
明确传递给组。
Ive也尝试使用fields
选项,但是它引入了更多问题。
有谁知道如何正确使用验证器并使用组实际上仅验证数据的子集。
答案 0 :(得分:0)
您为什么使用Assert\Collection
?这对于验证一组相似的对象/物品很有用
我认为您应该将$constraints = new Assert\Collection([
替换为$constraints = [
,以表示您应该使用简单的约束数组