snoop168
snoop168

Reputation: 404

Symfony Validation dependent on another property

Trying to validate if one field is not empty (length > 0) then the length of the field being validated must be a certain length (2 characters). It seems like an "Assert\Expression" might work in this situation but I am having trouble trying to find the length of the properties. It seems like you cannot call php functions within the Expression. The expression documentation mentions functions but maybe I do not understand it... Do I need to register my own function that simply return a strlen(). If so how do you register your own functions? Can someone explain if there is a way to do this, or maybe there is a better way than using Expression that I am overlooking...

/**
 * @var string
 *
 * @ORM\Column(name="plate", type="string", length=10)
 */
private $plate;

/**
 * @var string
 *
 * @ORM\Column(name="state", type="string", length=2)
 * @Assert\Expression(
 *     "strlen(this.getPlate()) == 0 or (strlen(this.getPlate()) > 0 and strlen(value) == 2)",
 *     message="Must be 2 characters"
 * )     
 */
private $state;

In the above case I get an error The function "strlen" does not exist around position 1

Upvotes: 1

Views: 1957

Answers (1)

jkrnak
jkrnak

Reputation: 956

Looks like you will need to register your own function. Have a look at the docs: https://symfony.com/doc/current/components/expression_language/extending.html#registering-functions

There is an example on lowercase, strlen should be very similar.

EDIT:

You can also use a callback validator.

/**
 * @Assert\Callback()
 */
public function validateState(ExecutionContextInterface $context)
{
    if (!empty($this->plate) && mb_strlen($this->state) !== 2) {
        $context->buildViolation('State must be 2 characters long')
            ->atPath('state')
            ->addViolation();
    }
}

But if you are planning to using this kind of validation in multiple places, you can write and register your own validator.

Upvotes: 1

Related Questions