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.
当前,您仅声明了操作的方法
.这里没用.
Currently, you've only declared the method
of your operation. This is useless here.
- normalizationContext =>normalization_context
- validationGroups =>validation_groups
此外,您在 GET
操作中声明了 mehtod
属性,而不是 method
属性.
Also you've declared a mehtod
property instead of method
within you GET
operation.
这篇关于Symfony NotBlank约束允许空白字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!