3

Today I found something strange about Symfony >=2.3 validators. I you use

$metadata->addPropertyConstraint('body', new Length(array('min' => 50)));

it allows empty inputs. I don't think it should do this or am I wrong?

Marin Bînzari
  • 5,208
  • 2
  • 26
  • 43
  • 4
    If you want to make sure it's not blank then you should combine it with `NotBlank`. If it automatically validated an empty value as invalid then you would never be able to have a field that could be null OR the other validation without having to roll your own. – qooplmao Aug 15 '14 at 11:59
  • @Qoop, about null values you're right but for what then we validate minimum length? – Marin Bînzari Aug 15 '14 at 12:23

1 Answers1

2

This is the expected behaviour.

Just think about the different use cases: a phone number can be optional, but if the user has entered a phone number, it should be at least 10 characters.

So you need to combine your Length constraint with a NotNull/NotBlank constraint.

See https://github.com/symfony/symfony/issues/10221#issuecomment-34769066 for more explanation.

Btw : there is actually a brainstorming about empty string handling https://github.com/symfony/symfony/issues/11956.

rpg600
  • 2,800
  • 18
  • 24