Search code examples
symfonysymfony4

Symfony @Assert\Type("string") validation passes with integer value


I have a problem with validation of a field of type string in symfony 4. Here is an example:

<?php

class Foo {
    
    /**
     * @Assert\NotNull
     * @Assert\Type("string")
     *
     * @var string
     */
    protected string $uid;
}

And when I send (PUT) request like this it passes:

{
    "uid": 5,
}

The validation is working the other way around. If I set the field to integer and pass some string like "test" is properly validated.


Solution

  • That is due to the fact that integers are automatically interpreted as strings when used as strings in PHP. You will want to use a regex constraint, the example in the docs does what you want. Something like this:

    <?php
    
    class Foo {
        
        /**
         * @Assert\NotNull
         * @Assert\Regex(
         *     pattern="/\d/",
         *     match=false,
         *     message="Your name cannot contain a number"
         * )
         *
         * @var string
         */
        protected string $uid;
    }