symfony2中的自定义验证

时间:2011-03-15 10:32:10

标签: symfony

我是symfony的新手。我决定用Symfony版本2移动我的轮子。

在我的用户表单中:

  • 我想验证数据库中电子邮件的唯一性。
  • 我想用确认密码字段验证密码。
  • 我可以在symfony2 doc中找到任何帮助。

6 个答案:

答案 0 :(得分:24)

这些东西花了我一段时间来追踪,所以这就是我想出来的。说实话,我不太确定User实体的getRoles()方法,但这只是我的测试设置。这样的上下文项目仅为了清楚起见而提供。

以下是一些有用的链接供进一步阅读:

我将这一切都设置为确保它作为UserProvider的安全性,因为我认为你可能正在这样做。我还假设您使用电子邮件作为用户名,但您不必这样做。您可以创建一个单独的用户名字段并使用它。有关详细信息,请参阅Security

实体(仅重要部分;省略了自动生成的getter / setter):     

namespace Acme\UserBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 *
 * list any fields here that must be unique
 * @DoctrineAssert\UniqueEntity(
 *     fields = { "email" }
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length="255", unique="true")
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length="128")
     */
    protected $password;

    /**
     * @ORM\Column(type="string", length="5")
     */
    protected $salt;

    /**
     * Create a new User object
     */
    public function __construct() {
        $this->initSalt();
    }

    /**
     * Generate a new salt - can't be done as prepersist because we need it before then
     */
    public function initSalt() {
        $this->salt = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);
    }

    /**
     * Is the provided user the same as "this"?
     *
     * @return bool
     */
    public function equals(UserInterface $user) {
        if($user->email !== $this->email) {
            return false;
        }

        return true;
    }

    /**
     * Remove sensitive information from the user object
     */
    public function eraseCredentials() {
        $this->password = "";
        $this->salt = "";
    }


    /**
     * Get the list of roles for the user
     *
     * @return string array
     */
    public function getRoles() {
        return array("ROLE_USER");
    }

    /**
     * Get the user's password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * Get the user's username
     *
     * We MUST have this to fulfill the requirements of UserInterface
     *
     * @return string
     */
    public function getUsername() {
        return $this->email;
    }

    /**
     * Get the user's "email"
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Get the user's salt
     *
     * @return string
     */
    public function getSalt() {
        return $this->salt;
    }

    /**
     * Convert this user to a string representation
     *
     * @return string
     */

    public function __toString() {
        return $this->email;
    }
}
?>

Form类:     

namespace Acme\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType {
    public function buildForm(FormBuilder $builder, array $options) {
        $builder->add('email');
        /* this field type lets you show two fields that represent just
           one field in the model and they both must match */
        $builder->add('password', 'repeated', array (
            'type'            => 'password',
            'first_name'      => "Password",
            'second_name'     => "Re-enter Password",
            'invalid_message' => "The passwords don't match!"
        ));
    }

    public function getName() {
        return 'user';
    }

    public function getDefaultOptions(array $options) {
        return array(
            'data_class' => 'Acme\UserBundle\Entity\User',
        );
    }
}
?>

控制者:     

namespace Acme\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\UserBundle\Entity\User;
use Acme\UserBundle\Form\Type\UserType;


class userController extends Controller
{
    public function newAction(Request $request) {
        $user = new User();
        $form = $this->createForm(new UserType(), $user);

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);

            if ($form->isValid()) {
                // encode the password
                $factory = $this->get('security.encoder_factory');
                $encoder = $factory->getEncoder($user);
                $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
                $user->setPassword($password);

                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($user);
                $em->flush();

                return $this->redirect($this->generateUrl('AcmeUserBundle_submitNewSuccess'));
            }
        }

        return $this->render('AcmeUserBundle:User:new.html.twig', array (
            'form' => $form->createView()
        ));
    }

    public function submitNewSuccessAction() {
        return $this->render("AcmeUserBundle:User:submitNewSuccess.html.twig");
    }

security.yml的相关部分:

security:
    encoders:
        Acme\UserBundle\Entity\User:
            algorithm: sha512
            iterations: 1
            encode_as_base64: true

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        main:
            entity: { class: Acme\UserBundle\Entity\User, property: email }

    firewalls:
        secured_area:
            pattern:    ^/
            form_login:
                check_path: /login_check
                login_path: /login
            logout:
                path:   /logout
                target: /demo/
            anonymous: ~

答案 1 :(得分:1)

查看http://github.com/friendsofsymfony有一个具有该功能的UserBundle。您还可以查看http://blog.bearwoods.com哪里有关于为Recaptcha添加自定义字段,约束和验证程序的博文。

如果你仍然遇到麻烦,那些资源应该让你开始走上正确的道路人们对Freenode网络上的#symfony-dev的irc通常很有帮助和友好。在Freenoce上还有一个通用频道#symfony,你可以在这里询问如何使用#symfony-dev用于开发Symfony2 Core的东西。

希望这有助于您推进项目。

答案 2 :(得分:1)

我认为在创建自定义验证器时需要注意的主要事项是getTargets()方法中指定的常量。

如果你改变了

self::PROPERTY_CONSTRAINT

为:

self::CLASS_CONSTRAINT

您应该能够访问实体的所有属性,而不仅仅是单个属性。


注意:如果使用注释来定义约束,则现在需要将定义验证器的注释移动到类的顶部,因为它现在适用于整个实体而不仅仅是单个属性。 / p>

答案 3 :(得分:0)

您应该能够从docs获得所需的一切。具体来说,constraints包含有关电子邮件检查的信息。还有关于撰写custom validators的文档。

答案 4 :(得分:0)

我在http://symfony.com/doc/2.0/book/validation.html

上完成了所有工作

我的配置:

validator.debit_card:
        class: My\Validator\Constraints\DebitCardValidator
        tags:
            - { name: validator.constraint_validator, alias: debit_card }

尝试将其与

一起使用
@assert:DebitCard
@assert:debitCard
@assert:debit_card

但它没有被触发?

答案 5 :(得分:-1)

来自数据库的唯一电子邮件

validation.yml

控制板\ ArticleBundle \实体\文章:     限制:         # - Symfony \ Bridge \ Doctrine \ Validator \ Constraints \ UniqueEntity:senderEmail          - Symfony \ Bridge \ Doctrine \ Validator \ Constraints \ UniqueEntity:{fields:senderEmail,message:此电子邮件已存在}

密码确认密码

    $builder->add('password', 'repeated', array(
       'first_name' => 'password',
       'second_name' => 'confirm',
       'type' => 'password',
       'required' => false,
    ));