Validate only if value is submitted


I have the following issue:

I have a form that has some input fields that are not required. If a user enters something, it should have for example a minimum, maximum length or match a regex. If a user does not enter something, validation should not happen on that particular field.


I have a field called postalcode that has a minimum length of 6 characters

->add('postalcode',new StringLength(array(
'min' => 6,
'messageMinimum' => 'you should enter at least 6 characters'

If nothing is submitted in the postalcode field the StringLength validator returns a message because nothing/NULL is less than 6, That's not want I want, because this field is not required, but if something is submitted it should have a minimum of 6 characters.

My question: Is there something available to solve this issue, or should I write a new validation class?


in your validation() method just wrap your validator in condition like this:

    public function validation()

        if( ! is_null($this->column) )
            $this->validate(new StringLength(array(
                // your validator values

        return $this->validationHasFailed() != true;

or you can just create new validator :)