Symfony NotBlank 约束允许空字符串 [英] Symfony NotBlank constraint allow blank string
问题描述
我正在使用 Symfony5
和 ApiPlatform
和 phpunit
进行测试
I'm working with Symfony5
and ApiPlatform
with phpunit
for the tests
我正在对现场验证进行测试.
I'm running tests on field validation.
我的问题来自这样一个事实,即我想限制用户在名为 name
的属性中输入空白字符串的可能性,如下所示:
My issue comes from the fact that I want to restrain the user's possiblity to enter a blank string in a property named name
as follow :
/**
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"cons:read", "cons:list"}},
* "denormalization_context"={"groups"={"cons:write"}}
* },
* collectionOperations={
* "get"={
* "mehtod"="GET",
* "normalization_context"={"groups"={"cons:list"}},
* },
* "post"={
* "method"="POST"
* "normalizationContext"={"groups"={"cons:write"}},
* "validationGroups"={"create"}
* }
* }
* )
* @ORM\Entity(repositoryClass=ConsultationTypeRepository::class)
*/
class ClassName
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups({"cons:read", "cons:list", "some:read", "thing:read"})
*/
private $id;
/**
* @ORM\Column(type="string", length=255, nullable=false)
* @Groups({"cons:read", "cons:write", "cons:list", "some:read", "thing:read", "availability:read"})
* @Assert\NotBlank (
* groups={"create"},
* message="Le nom ne peut pas être vide."
* )
* @Assert\Length(
* max = 255,
* maxMessage = "Le nom ne peut pas excéder 255 charactères",
* allowEmptyString = false
* )
* @Assert\Regex(
* pattern="/\d/",
* match=false,
* message="Le nom ne peut pas contenir de nombre"
* )
*/
private $name;
这是我的测试:
public function testRoleAdminCanNotPostConsultationWithBlankName(): void
{
$body = '{ "name": ""}';
$res = $this->buildPostPutRequest(
Actions::POST,
self::TYPE_CONSULTATION_ROUTE,
$body,
self::ADMIN_CREDENTIALS
);
$this->assertResponseStatusCodeSame(400);
}
现在我收到一个 201
而不是预期的 400
.
Now I receive a 201
instead of the expected 400
.
虽然其他有关正则表达式或字符串长度的测试按预期返回 400
.
While other tests concerning the regex or the length of the string return 400
as expected.
我不明白为什么 NotBlank()
在这个测试中似乎没有触发.
I don't understand why the NotBlank()
seem to not trigger on this test.
有什么想法吗?
推荐答案
我认为这是因为您已经使用驼峰式而不是蛇式来声明您的 post
操作属性.驼峰式大小写必须仅用于 ApiResource
注释的顶层.
I think this is because you've declared your post
operations attributes using camel case instead of snake case. Camel case must be used at the top-level of the ApiResource
annotation only.
目前,您只声明了操作的method
.这在这里没用.
Currently, you've only declared the method
of your operation. This is useless here.
- normalizationContext =>normalization_context
- validationGroups =>验证组
您还声明了 mehtod
属性而不是 method
在您的 GET
操作中.
Also you've declared a mehtod
property instead of method
within you GET
operation.
这篇关于Symfony NotBlank 约束允许空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!