Reputation: 25
I'm trying to set the same phone regex everywhere on my website, using a pattern defined in the app/config/parameters.yml
parameters:
phone_regex: /^[+][3][3]\d{9}$/
How can i retrieve this patern in my entities assert annotations ?
/**
* @var string
* @Assert\NotBlank(message = "notBlank")
* @Assert\Regex(
* pattern="%phone_regex%",
* message="phone"
* )
* @ORM\Column(name="contact_phone", type="string", length=255)
*/
private $contactPhone;
The code above does not work, it generates html without the regex
<input type="text" id="client_contactPhone" name="client[contactPhone]" required="required" maxlength="255" pattern=".*phone_regex.*" class="form-control">
Upvotes: 2
Views: 2675
Reputation: 8276
Joe has a good solution, but my question is - why have this as a parameter at all? Is this something you would ever plan on overriding in the future? I'm guessing not. Instead, you could simply make a class w/constant that holds the information you need:
class Phone
{
const VALID_REGEX = '/^[+][3][3]\d{9}$/';
}
Then, for your annotations:
/**
* @var string
* @Assert\NotBlank(message = "notBlank")
* @Assert\Regex(
* pattern=Phone::VALID_REGEX,
* message="phone"
* )
* @ORM\Column(name="contact_phone", type="string", length=255)
*/
private $contactPhone;
This way you're still using the Regex validator and not reinventing the wheel with another custom validation type.
The other main benefit is that you can use this everywhere in your code without actually having to inject the parameter to a service, or anything else. Plus it's easy to access class constants from Twig.
Upvotes: 3
Reputation: 2436
The only way you can do this is by creating your own custom validation constraint. Pretty easy actually once you've done it in one case.
A good documentation can be found here: http://symfony.com/doc/current/validation/custom_constraint.html
Basically a summary what you could do:
There is currently no known option to use parameters in the existing annotation.
Upvotes: 4