How to make an index of an array not be required in a validation with Respect Validation Key?

1

I'm using Respect\Validation to validate some fields on my form. I am using the Validator::key() method to be able to validate each value present in an index of array that is sent from that form.

I have the following code:

Validator::key('nome', Validator::notOptional()->stringType())
      ->key('tipo', Validator::in(['f', 'j']))
      ->key('telefone', Validator::optional(
            Validator::regex('/^\(\d{2}\)\d{4}-\d{4}$/')
        ))
      ->key('celular', Validator::optional(
            Validator::regex('/^\(\d{2}\)\d{5}-\d{4}$/')
        ))
      ->key('email', Validator::email()->notOptional())
      ->key('cidade', Validator::notOptional()->stringType());

The value telefone and celular used Validator::optional() so that the fields did not need to exist, but if they existed, they should be validated.

But when I submit the form without filling celular , I get the following error:

  

Key cell phone must be present

I would like to know: how can I validate a key in an array with Respect Validation, but only if it exists?

References:

link

    
asked by anonymous 26.01.2017 / 18:21

1 answer

3

From the documentation :

The key method has 3 parameters, where the third is "required".

I imagine it would look like this:

->key('celular', Validator::regex('/^\(\d{2}\)\d{5}-\d{4}$/'), false)

The documentation has this explanation:

v::key(string $name, v $validator, boolean $mandatory = true)
    
26.01.2017 / 18:33