我尝试创建我的验证器,但它不起作用。 文档没有帮助,因为它只关心对象验证,并且有一个数组验证示例。
我试图根据随数据一起发送的字段验证我的数据。 因此,我在请求中有一个字段type
,该字段credentials
,google
或facebook
,并且根据此字段值,应验证其他字段。 当然,必须首先验证type
。
我尝试的是遵循集合的文档,但我只得到意外的异常和结果。有时错误,有时没有,事情只是没有按预期工作。
给定以下示例:
use SymfonyComponentValidatorConstraints as Assert;
use SymfonyComponentValidatorValidation;
require_once(__DIR__ . "/../vendor/autoload.php");
$validator = Validation::createValidator();
$constraints = new AssertCollection([
"type" => [
new AssertRequired([
"groups" => ["type"],
"constraints" => new AssertChoice([
"choices" => ["credentials", "facebook", "google"],
])
]),
],
"username" => [
new AssertNotBlank([
"groups" => ["credentials", "facebook", "google"]
])
],
"password" => [
new AssertNotBlank([
"groups" => ["credentials"]
]),
new AssertLength([
"min" => 6,
"groups" => ["credentials"]
]),
],
"passwordConfirm" => [
new AssertNotBlank([
"groups" => ["credentials"],
]),
new AssertIdenticalTo([
"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"
传递给了组。 我也尝试使用fields
选项,但它引入了更多问题。 有谁知道如何正确使用验证器并使用组实际上只验证数据的子集。
为什么要使用AssertCollection
? 这对于验证类似对象/项目的数组很有用
我认为你应该用$constraints = [
替换:$constraints = new AssertCollection([
,就像你应该使用一个普通的约束数组