我有这个表格: class RegistrationFormType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('email', EmailType::class, [ 'constraints' => [ new NotBlank(), ] ]) ->add('username') ->add('password') ; } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'app_user_register'; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => User::class, 'allow_extra_fields' => true, 'csrf_protection' => false, ]); }}我在控制器中的 api:/** * @Route("/api/register") * @Method("POST") * @param Request $request * * @return JsonResponse */public function register( UserService $userService, Request $request){ try { return $userService->register(json_decode($request->getContent(), true)); } catch (\Exception $e) { return $this->json([ 'status' => Response::HTTP_INTERNAL_SERVER_ERROR, 'result' => $e->getMessage() ]); }}我的服务职能:public function register($formData){ $user = new User(); $form = $this->formFactory->create(RegistrationFormType::class, $user); $form->submit($formData); if ($form->isSubmitted() && $form->isValid()) { $this->entityManager->persist($user); $this->entityManager->flush(); return new JsonResponse([ 'status' => Response::HTTP_OK, 'result' => true ]); }当我尝试在邮递员中调用 api /api/register 时{ "username": "test1", "email": "test1", "password": "123456"}我得到200 code,但通常应该删除错误,因为电子邮件无效,因为我在表单创建中设置了字段电子邮件应该采用电子邮件格式,即使我在电子邮件中放入一个空字符串,我也会得到200 code. 所以似乎验证不起作用。
2 回答
倚天杖
TA贡献1828条经验 获得超3个赞
尝试 :
->add('email', EmailType::class, [
'constraints' => [
new NotBlank(),
new Email(),
]
])
并添加到您的实体:
/**
* @Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* checkMX = true
* )
*/
protected $email;
- 2 回答
- 0 关注
- 148 浏览
添加回答
举报
0/150
提交
取消