标签: symfony-validator

使用symfony2.3对单元测试验证器约束

我想使用约束来制作一个测试单元,但是在运行测试时我遇到了这个错误

这是我的不同类和运行phpunit后获取错误

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Age18 extends Constraint
{
	public $message = 'Vous devez avoir 18 ans.';

}


use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class Age18Validator extends ConstraintValidator
{
	public function validate($dateNaissance, Constraint $constraint)
	{
		if ($dateNaissance > new \DateTime("18 years ago"))
		{
			$this->context->addViolation($constraint->message);
		}
	}
}


use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class Age18ValidatorTest extends \PHPUnit_Framework_TestCase
{
	private $constraint;

	public function setUp()
	{
		$this->constraint = $this->getMock('Symfony\Component\Validator\Constraint');
	}

	public function testValidate()
	{
		/*ConstraintValidator*/
		$validator = new Age18Validator();
		$context …
Run Code Online (Sandbox Code Playgroud)

php phpunit unit-testing symfony symfony-validator

3
推荐指数
1
解决办法
2675
查看次数

找不到类“doctrine.orm.validator.unique”

所以我不确定这里的问题是什么,或者这个类是如何加载的。但我的模型(或者他们实际所说的实体)看起来像这样:

<?php

namespace ImageUploader\Models;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @UniqueEntity(fields="userName")
 * @UniqueEntity(fields="email")
 */
class User {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=32, nullable=false)
     * @Assert\NotBlank()
     */
    protected $firstName;

    /**
     * @ORM\Column(type="string", length=32, nullable=false)
     * @Assert\NotBlank()
     */
    protected $lastName;

    /**
     * @ORM\Column(type="string", length=100, unique=true, nullable=false)
     * @Assert\NotBlank(
     *    message = "Username cannot be blank"
     * )
     */
    protected $userName;

    /**
     * @ORM\Column(type="string", …
Run Code Online (Sandbox Code Playgroud)

php doctrine-orm symfony-validator

3
推荐指数
1
解决办法
2657
查看次数

如何比较验证中的日期?

我正在尝试比较验证中的日期.文档说这是可能的,但没有记录.我正在使用注释,我希望一个日期晚于另一个.我该怎么做呢?

在此输入图像描述

annotations symfony symfony-validator

3
推荐指数
1
解决办法
2133
查看次数

无法使用没有data_class的表单使用Callback断言

我正在创建一个名为IntervalType的自定义FormType.我IntervalType将有两个字段,start并且end,将是整型的.此自定义FormType将始终不使用data_class.

我想添加一个约束来保证start低于end.

如何在FormType中直接使用Symfony\Component\Validator\Constraints\Callback data_class

这是我的IntervalType,仅供参考:

// src/AppBundle/Form/Type/IntervalType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Validator\Constraints\NotBlank;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('start', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
            ->add('end', IntegerType::class, array(
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

symfony-forms symfony symfony-validator

3
推荐指数
1
解决办法
3879
查看次数

Symfony4 : 注释不存在,或无法自动加载 (Symfony\Component\Validator\Constraints)

我正在开发 Symfony4 应用程序,但出现此错误:

[语义错误] 属性 App\Entity\Product::$brochure 中的注释“@Symfony\Component\Validator\Constraints\NotBlank”不存在,或无法自动加载。

这是Product课程:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $name;
    
    /**
     * @ORM\Column(type="decimal", scale=2, nullable=true)
     */
    private $price;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="string")
     *
     * @Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
     * @Assert\File(mimeTypes={ "application/pdf" })
     */
    private $brochure;
    
    public …
Run Code Online (Sandbox Code Playgroud)

php annotations symfony symfony-validator symfony4

3
推荐指数
1
解决办法
5584
查看次数

Symfony - 在 INSERT、UPDATE 或 DELETE 中以不同方式验证实体

我想在创建、更新或删除实体时以不同的方式验证实体原则。

我的实体类中有一个实体约束验证器。

// src/AppBundle/Entity/AcmeEntity.php
use AppBundle\Validator\Constraints as AcmeAssert;

/**
* @AcmeAssert\CustomConstraint
*/
class AcmeEntity
{
    // ...
    protected $name;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

在我的 CustomConstraint 中,我想确定实体是否会被更新、创建或删除以执行特定的验证器。

使用工作单元是一种解决方案吗?

做这个的最好方法是什么?

我认为这个问题在很多应用程序中都很常见?

谢谢大家 ;)

symfony-forms symfony doctrine-orm symfony-validator

2
推荐指数
1
解决办法
1950
查看次数

如何通过使用EntityType表单类型来避免复选框列表中的空值?

我有一个这样的表单字段:

$form->add('tags', EntityType:class, array(
    'class' => Tags::class,
    'multiple' => true,
    'expanded' => true,
    'required' => true,
));
Run Code Online (Sandbox Code Playgroud)

这提供了一个很好的复选框列表,我需要确保在提交表单后至少选择了一个选项,但即使required选项true不起作用,我尝试使用NotBlank()NotNull()约束,也不起作用(即表单)已验证).

如何通过使用EntityType表单类型来避免复选框列表中的空值?

symfony-forms symfony symfony-validator

2
推荐指数
1
解决办法
143
查看次数

如何创建限制最大子项的约束

假设我有两个实体Bus并且它们之间People存在关系OneToMany.巴士最多可容纳10人.

如何创建约束来控制这个?

例如:

* @MyAssert\ParentMaxChild(max=10)

* @ORM\ManyToOne(targetEntity="Webface\CharacterBundle\Entity\Bus", inversedBy="wac")
* @ORM\JoinColumn(name="bus_id", referencedColumnName="id", nullable=false)

private $bus;
Run Code Online (Sandbox Code Playgroud)

symfony symfony-validator

2
推荐指数
1
解决办法
39
查看次数

Symfony表单验证约束表达式

我有表单,需要创建内联验证:

$builder
        ->add('Count1', 'integer', [
            'data'        => 1,
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])
        ->add('Count2', 'integer', [
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])
        ->add('Count3', 'integer', [
            'data'        => 0,
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])
Run Code Online (Sandbox Code Playgroud)

白色内联验证如何表达规则

  1. Count2> = Count1
  2. Count3 <= Count2
  3. Count2> = $ someVariable

validation symfony-forms symfony symfony-validator

2
推荐指数
1
解决办法
2862
查看次数

如何验证restful api中post的数据

我需要在插入数据库之前验证一些数据,为此我创建了一个从实体返回无效字段的小服务。验证单个实体时它工作正常。

class EntityValidator
{
    protected $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    public function validate($entity)
    {
        $errors = $this->validator->validate($entity);
        $response = null;
        if ($errors->count()) {
            foreach ($errors as $error) {
                $response[$error->getPropertyPath()] = $error->getMessage();
            }
        }

        return $response;
    }
}
Run Code Online (Sandbox Code Playgroud)

但我一直在努力验证更复杂的问题,例如:这是一个restful api端点,它接收带有user_id和帖子正文中百分比的json,它将验证实体以查看它是否与symfony验证器约束映射正确。

public function create(Request $request, EntityValidator $entityValidator)
{
    $data = json_decode($request->getContent(), true);
    $entityExample = new EntityExample();
    $entityExample
         ->setUserId($data['user_id'])
         ->setPercentage($data['percentage'])
    ;
    $errors = $entityValidator->validate($entityExample);
    // .. do other things ..
    return new JsonResponse($errors);    
}
Run Code Online (Sandbox Code Playgroud)

但是假设我收到一个数据数组,并且我要一次插入多行,并且有一个业务逻辑说“用户的百分比总和需要为 100”

public function …
Run Code Online (Sandbox Code Playgroud)

php model-view-controller code-structure symfony symfony-validator

2
推荐指数
1
解决办法
7832
查看次数

Symfony 中 RFC 2822、3.6.2 的电子邮件合规性和验证

我在通过Symfony Email Constraint验证用户电子邮件地址,然后尝试通过Swiftmailer向该用户发送邮件时遇到问题。

假设我的用户正在使用name@@gmail.com注册(双@是示例中的故意拼写错误)。Symfony 中的电子邮件约束验证已成功验证这一点,并且在我的数据库中创建了该用户。

但是当我尝试使用 Swiftmailer 发送邮件时,出现500 错误

给定的邮箱地址 [name@@gmail.com] 不符合 RFC 2822, 3.6.2。

来自 Swiftmailer 本身。

php swiftmailer symfony symfony-validator

2
推荐指数
1
解决办法
2186
查看次数

在Core之外使用Symfony2 Validator注释

如何配置Symfony2 Validator以使用Core之外的注释?

在核心中,您将执行以下操作:

$container->loadFromExtension('framework', array(
  'validation' => array(
    'enable_annotations' => true,
  ),
));
Run Code Online (Sandbox Code Playgroud)

摘自:http://symfony.com/doc/2.0/book/validation.html#configuration

现在要进行验证工作,规则是在方法loadValidatorMetadata(ClassMetadata $ metadata)中设置的,它可以工作,但我更喜欢注释.

示例具有验证注释的实体和用于设置验证规则的备用php方法:

<?php

namespace Foo\BarBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;


/**
 * @ORM\Entity(repositoryClass="Foo\BarBundle\Entity\Repository\FooRepository")
 * @ORM\Table(name="foo")
 */
class Foo {


    /**
     * @ORM\Column(type="integer", name="bar")
     * @Assert\Type(
     *     type="integer",
     *     message="The value {{ value }} is not a valid {{ type }}."
     * )
     */
    protected $bar;


    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('bar', new Assert\Type(array(
            'type'    => …
Run Code Online (Sandbox Code Playgroud)

symfony symfony-validator

1
推荐指数
1
解决办法
1334
查看次数

Symfony中ConstraintViolationListInterface异常

我需要将类型的对象转换ConstraintViolationListInterface为单个异常以进行进一步的记录,其中消息是验证失败时列表中每个约束违例的消息的串联。

显然,我无法使用验证在每个捆绑软件中重复一个foreach循环来实现这一点,因此我在考虑再创建一个捆绑软件,以提供一个接受ConstraintViolationListInterface并返回单个异常的简单服务。Symfony中对此有标准解决方案吗?似乎我需要编写此服务很奇怪,这个问题对我来说似乎很常见。

php symfony symfony-validator

1
推荐指数
1
解决办法
1162
查看次数