user2474622
user2474622

Reputation:

Create a custom validation constraint that will check if a word begin with an uppercase - Symfony 2

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

Answers (3)

Pi Wi
Pi Wi

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

user2474622
user2474622

Reputation:

Find it myself regarding php.net :

if ($value[0]!=strtoupper($value[0])) {
...
}

Upvotes: 0

Nicolai Fröhlich
Nicolai Fröhlich

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

Related Questions