Markus
Markus

Reputation: 4681

How can I set global charset for Symfony validator?

I am using Symfony-Length-Contraint several times in my php-project. My Symfony-Version is 2.5.10

Unfortunately, my charset is ISO-8859-1, Symfony-Length-Constraint defaults to UTF-8.

Well, I can change every @Assert\Length like this:

* @Assert\Length(charset="ISO-8859-15")

to have validation work probably.

But I want to set this charset globally for my project, instead of setting charset for each Length-Assertion. How/Can I do this?

Upvotes: 1

Views: 702

Answers (1)

Peter Bailey
Peter Bailey

Reputation: 105878

That is a good question - You can certainly subclass the constraint to achieve this

Assuming 2.6 defaults:

src/AppBundle/Validator/Constraints/Length.php

<?php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraints;

/**
 * @Annotation
 *
 * @api
 */
class Length extends Constraints\Length
{
    public $charset = 'ISO-8859-1';
}

Then, in your entity files or wherever

use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\Constraints as CustomAssert;

(...)

* @CustomAssert\Length(min=123)

But I'll be honest, I'm not sure if this is the best way.

Upvotes: 1

Related Questions