PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

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

 February 16, 2022     symfony, symfony4     No comments   

Issue

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;
}


Answered By - Arleigh Hix
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing