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

Asked

Viewed 63 times

1

I’m using the Respect\Validation to validate some fields in my form. I am using the method Validator::key() to be able to validate each value in an index of array that is sent from this 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 did exist, they must be validated.

But when I send the form without completing it celular, I get the following error:

Key celular must be present

I wonder: how can I validate a key of an array with Respect Validation, but only if it exists?

References:

https://github.com/Respect/Validation/blob/master/docs/Key.md

1 answer

3


From what I understood from documentation:

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

I imagine it would be so:

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

In the documentation there is this explanation:

v::key(string $name, v $validator, boolean $mandatory = true)
  • Yeah, that worked. This third parameter makes the value only valid if it doesn’t exist. Thank you very much. + 1

  • Mark as correct =]

  • kkkk, I usually take a long time to score anyway. It’s a procedure I was taught here on the site. But rest assured, I’ll probably mark it yes.

  • 1

    I imagine it is interesting this "procedure" when it comes to some algorithm or solution that may be different, in this case it has no secret is the signature of the médoto. But feel free to schedule any time you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.