在自定义操作控制器中进行验证 [英] Validation in custom operation controller

查看:123
本文介绍了在自定义操作控制器中进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅在api平台上的自定义操作上进行验证,但是它不起作用.

I'm trying to do a validation only on a custom operation on api platform but it doesn't work.

仅在验证没有错误但无论如何都更改了密码的情况下,我才想更改密码.

I would like to change the password only if there is no error in the validation but in any case the password is changed.

如果我从验证批注中删除验证组,它将起作用.

If I remove the validation groups from the validation annotations it works.

例如,如果我将 @Assert \ NotBlank(groups = {"put-reset-password"})替换为 @Assert \ NotBlank 验证通行证.

for example if i replace @Assert\NotBlank(groups={"put-reset-password"}) with @Assert\NotBlank the validation pass.

这是实体的代码:

  "CHANGE-PASSWORD"={
    "method"="PUT",
     "path"="/users/change-password/{id}",
     controller"="App\Controller\ChangePasswordController",
     "access_control"="is_granted('EDIT-PASSWORD', previous_object) and object == user",
     "openapi_context"={
        "summary"="Change Password"
     },
     "denormalization_context"={
        "groups"={"put-reset-password"}
     },
     "validation_groups"={"put-reset-password"},
  },

这是我的控制器

public function __invoke(User $data)
{

    // Validate data and handle validation errors
    $this->validator->validate($data);

    $data->setPassword($this->userPasswordEncoder->encodePassword($data, $data->getNewPassword()));


    $this->entityManager->flush();
    $token = $this->tokenManager->create($data);


    return $data;
}

这是我使用验证组的属性之一.

and here is one of my attributes in which i use validation group.

/**
 * @Groups({"put-reset-password"})
 * @Assert\NotBlank(groups={"put-reset-password"})
 * @UserPassword(groups={"put-reset-password"})
 */
private $oldPassword;

有什么问题吗?

推荐答案

这是奇怪的行为.您得到null可能是因为您使用了界面

This is strange behavior. You get null probably because you use interface

使用ApiPlatform \ Core \ Validator \ ValidatorInterface;

如果使用inface,请使用Symfony \ Component \ Validator \ Validator \ ValidatorInterface ,您必须是对象 ConstraintViolationListInterface .

If use inface use Symfony\Component\Validator\Validator\ValidatorInterface you must be get object ConstraintViolationListInterface.

我有类似的问题.以下解决方案对我有帮助:

I have a similar problem. The following solution helped me:

/**
 * @Groups({"put-reset-password"})
 * @Assert\NotBlank(groups={"Default", "put-reset-password"})
 * @UserPassword(groups={"put-reset-password"})
 */
private $oldPassword;

这很奇怪,但是在添加默认" 后,我的验证已在我的自定义操作中完成.

It's strange, but after added "Default" my validation is worked in my custom operation.

有用的链接:

https://symfony.com/doc/current/validation/groups.html https://symfony.com/doc/current/validation/sequence_provider.html

P.S.对不起,我的英语不好.

P.S. Sorry for my bad english.

这篇关于在自定义操作控制器中进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆