How to define a set of values ​​to restrict NotEqualTo?

When using the NotEqualTo validator constraint , I want to define more than one value.

Here's how it is used for a single value:

# src/SocialBundle/Resources/config/validation.yml
Acme\SocialBundle\Entity\Person:
    properties:
        age:
            - NotEqualTo:
                value: 15

But how can I define a set (array) of values? I tried

            - NotEqualTo:
                value: 15
                value: 16
                value: 17

and

            - NotEqualTo:
                value: [15, 16, 17]

but both approaches did not help.

+4
source share
1 answer

I believe that you may have more than one limitation.

Acme\SocialBundle\Entity\Person:
    properties:
        age:
            - NotEqualTo: { value: 15 }
            - NotEqualTo: { value: 16 }
            - NotEqualTo: { value: 17 }

Or provide a callback validator

Acme\SocialBundle\Entity\Person:
    properties:
        age:
            - Callback: [validateNotOfAge]

.

<?php

namespace Acme\SocialBundle\Entity;

use Symfony\Component\Validator\ExecutionContextInterface;

class Person
{
    public function validateNotOfAge(ExecutionContextInterface $context)
    {
        if (in_array($this->age, array(
            15, 16, 17
        ))) {
            $context->addViolationAt(
                'age',
                'This age is not permitted',
                array(),
                null
            );
        }
    }
}

Or, if you have Symfony 2.4, you can use a new validator Expressionthat uses the ExpressionLanguage component.

Acme\SocialBundle\Entity\Person:
    properties:
        age:
            - Expression:
                expression: "this.getAge() not in [15, 16, 17]"
+5
source

Source: https://habr.com/ru/post/1531133/


All Articles