Thomas Vangelooven
Thomas Vangelooven

Reputation: 1709

Can I use Symfony's validation constraint NotEqualTo case insensitive

I am trying to use Symfony's Validation Constraint NotEqualTo to prevent usage of a certain string value.

As the documentation states this should be possible using the NotEqualTo constraint. This works, albeit in a case sensitive manner. However I would need this to also work in a case insensitive manner. I could solve this by creating a custom constraint, but maybe I'm just overlooking a more trival solution.

class Foo
{
    /**
     * @Assert\Length(
     *     min=4,
     *     max=150
     * )
     * @Assert\NotEqualTo(
     *     value="bar"
     * )
     */
    private $name;
}

In this example the reserved keyword is bar. Symfony will not allow bar but will allow Bar, BAR, BaR, ...

Can I use Symfony's validation constraint NotEqualTo in a case insensitive manner?

Upvotes: 2

Views: 1085

Answers (2)

Jakumi
Jakumi

Reputation: 8374

NotEqualTo compares its values via !=. Since 'bar' != 'BAR' you can't turn it around.

However, you probably could either easily add validation with a callback function to compare the lowercase versions of both values. Or your could write your own Constraint & Validator: https://symfony.com/doc/current/validation/custom_constraint.html

You probably want to extend Symfony/Component/Validator/AbstractComparison (already provides the "value" attribute/property) and the respective Validator.

In the spirit of full disclosure: OP has found a better way to solve their problem: Using the built-in Regex constraint (see answer below).

Upvotes: 1

Thomas Vangelooven
Thomas Vangelooven

Reputation: 1709

This is not possible with NotEqualTo, as confirmed before.

An easy way to solve the problem is by using Regex from the String Constraints

 /**
  * @Assert\Regex(
  *     pattern="/^(bar)$/i",
  *     match=false,
  *     message="'Bar' is a reserved name",
  * )
  */
 private $name;

It is also possible to create your own custom constraint. But I feel not writing code safer.

Upvotes: 2

Related Questions