Symfony 5注册表验证不起作用



我只是第一次学习Symfony。

表单验证没有按预期工作,我确实按照Symfony文档留下了锅炉板代码,我已经阅读了其他堆栈溢出文章和文档10次,看看我是否遗漏了什么,但我想不通。

客户端验证已经关闭,这对测试服务器端验证基本上很有效。但是在提交表单时,即使是空表单和无效数据,isValid((方法也会返回true。我在Entity和formType中都添加了约束,但它只是绕过了所有内容,我知道这是事实,因为异常是由数据库或密码编码方法引发的。

下面我有一个简单的代码示例,请检查:

ps:这是一个虚拟的学习项目,这是代码:

//AppEntityMyFavorite.php
//AppControllerRegistrationController:
<?php
namespace AppController;
use AppEntityMyFavorite;
use AppFormRegistrationFormType;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCore
EncoderUserPasswordEncoderInterface;
use SymfonyComponentValidatorValidatorValidatorInterface;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="app_register")
*/
public function register(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,        
ValidatorInterface $validator): Response
{
$user = new MyFavorite();
$form = $this->createForm(
RegistrationFormType::class, $user
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $this->redirectToRoute('myfav_vault');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView()
]);
}
}

//AppEntityMyFavorite
<?php
namespace AppEntity;
use AppRepositoryMyFavoriteRepository;
use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentSecurityCoreUserUserInterface;
//-> Bringing in the Validator Constraints as Assert
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMEntity(repositoryClass=MyFavoriteRepository::class)
* @UniqueEntity(fields={"uniqueCode"},
message="There is already an   account with this uniqueCode")
*/
class MyFavorite implements UserInterface
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=11, unique=true)
* -> Adding my first custom assertion:
* @AssertRegex("/^[a-zA-Z0-9]{3}-[a-zA-Z0-9]{3}-[a-zA-Z0-9]. {3}$/")
* @AssertLength(
*    min = 11,
*    max = 11
* )
*/
private $uniqueCode;
/**
* @ORMColumn(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORMColumn(type="string")
*/
private $password;
/**
* @ORMColumn(type="string", length=100)
* @AssertNotBlank
*/
private $name;

public function getId(): ?int
{
return $this->id;
}
public function getUniqueCode(): ?string
{
return $this->uniqueCode;
}
public function setUniqueCode(string $uniqueCode): self
{
$this->uniqueCode = $uniqueCode;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->uniqueCode;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
//not needed when using the "bcrypt" algorithm insecurity.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user,    
// $this->plainPassword = null;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getExpiry(): ?DateTimeInterface
{
return $this->expiry;
}
public function setExpiry(?DateTimeInterface $expiry): self
{
$this->expiry = $expiry;
return $this;
}
}    

//AppFormRegistrationFormType
<?php
namespace AppForm;
use AppEntityMyFavorite;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypePasswordType;
//-> Getting basic TextType
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsIsTrue;
use SymfonyComponentValidatorConstraintsLength;
use SymfonyComponentValidatorConstraintsNotBlank;
use SymfonyComponentValidatorConstraintsRegex;
//-> Testing out with Regex and String
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('uniqueCode')
->add('plainPassword', PasswordType::class, [
// instead of being set onto the object directly,
// this is read and encoded in the controller
'mapped' => false,
'constraints' => [
new NotBlank([
'message' => 'Please enter a password',
]),
//-> I am removing this as I do not want to provide options for min/max length
/*new Length([
'min' => 6,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),*/
],
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => MyFavorite::class,
//->Im going to turn of form validation on the client to see if the validation works on the server:
'validation_groups' => false
]);
}
}

//register.html.twig:


{% extends 'base.html.twig' %}
{% block title %}Register{% endblock %}
{% block body %}
{% for flashError in app.flashes('verify_email_error') %}
<div class="alert alert-danger" role="alert">{{ flashError }}</div>
{% endfor %}
<h1>Register</h1>

{{ form_start(registrationForm, {'attr': {'novalidate':'novalidate'}}) }}
{# This line had to be added manually so the form comes at the right place, some how all fields were not included #}
{{ form_row(registrationForm.name) }}
{{ form_row(registrationForm.uniqueCode) }}
{{ form_row(registrationForm.plainPassword, {
label: 'Password'
}) }}

<button type="submit" class="btn">Register</button>
{{ form_end(registrationForm) }}
{% endblock %}

调查结果:

提交完全空的表单时:encodePassword((抛出一个异常,因为密码字段为null,它需要字符串,(它甚至不应该进入这个阶段,因为我认为isValid((应该返回false?(

提交时使用密码和所有其他空值:绕过所有内容,只有数据库抛出异常。

提交uniqueCode的错误模式:验证器甚至不识别任何东西,每次都会通过它

handleRequest((方法没有抛出任何异常或返回false,除了密码,我得到了一个非常丑陋的错误,说密码的参数2不能为null,很明显,验证没有发生,isValid((返回true。

错误异常来自数据库

当我试图插入一个具有错误模式的唯一代码时,它会被插入,没有问题,当名称为空时,它通过了验证,但数据库抛出异常,当密码字段为空时,它仍然通过验证,

Symfony医生说:

handleRequest((方法将数据写回同一对象

然后我们验证数据:

"在上一节中,您了解了如何使用有效或无效数据提交表单。在Symfony中,问题不在于"表单"是否有效,而是在表单应用了提交的数据后,基础对象(本例中为$task(是否有效。调用$form->isValid((是一个快捷方式,用于询问$task对象是否具有有效数据">

我试着查看ValidatorInterface文档,但它清楚地表明:"大多数时候,您不会直接与验证器服务交互,也不需要担心打印出错误。大多数情况下,在处理提交的表单数据时,您将间接使用验证。有关更多信息,请参阅如何验证Symfony表单">

我在这里错过了什么?

这不是Stackoverflow的正确格式,但我们可以看到在关闭之前我们可以走多远。可能需要继续访问Reddit Symfony论坛。

从小处着手,让以下操作发挥作用。请注意,没有实体或其他事情在进行。只想让自己相信验证的基本原理确实有效:

class RegistrationController extends AbstractController
{
public function register(Request $request)
{
$form = $this->createFormBuilder()
->add('username', TextType::class, [
'constraints' => new NotBlank(['message' => 'User name cannot be blank'])
])
->add('save', SubmitType::class, ['label' => 'Register'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dump('Validated');
}
return $this->render('user/register.html.twig',['form' => $form->createView()]);
}
}
# user/register.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h1>Register Form</h1>
{{ form_start(form, {'attr':{'novalidate':'novalidate'}}) }}
{{ form_end(form) }}
{% endblock %}

最新更新