Reputation:
I've followed this tutorial : http://symfony.com/doc/current/cookbook/validation/custom_constraint.html to create a custom validation constraint. I made it work, no problem. The tutorial explains how to create a constraint that will only allow a user to type alphanumeric characters into a field. What I want is to do create a constraint that will force the user to type a string beginning by an uppercase.
I guess I have to change this part of my function :
public function validate($value, Constraint $constraint)
{
if (!preg_match('/^[a-zA-Za0-9]+$/', $value, $matches)) {
$this->context->addViolation($constraint->message, array('%string%' => $value));
}
But I'm too new in php, and I don't know the syntax of the constraint I want.
Upvotes: 1
Views: 1924
Reputation: 1085
Better solution is to use Regex validation constraints: http://symfony.com/doc/current/reference/constraints/Regex.html
Example with annotation:
class MyEntity
{
/**
* @Assert\Regex(
* pattern="/^[A-Z]/",
* match=false,
* message="Your name cannot contain a number"
* )
*/
protected $string;
}
Upvotes: 1
Reputation:
Find it myself regarding php.net :
if ($value[0]!=strtoupper($value[0])) {
...
}
Upvotes: 0
Reputation: 52493
if (!preg_match('/^[A-Z]/', $value, $matches)) {
$this->context->addViolation( /* .. */ );
}
^
= begins with
[A-Z]
= one of A ... Z ( an uppercase letter )
Upvotes: 0