Variable validation required if

Asked

Viewed 4,227 times

5

'tipo'              => 'required',
'cpf'               => 'required_if:tipo,F|cpf',
'rg'                => 'required_if:tipo,F',
'cnpj'              => 'required_if:tipo,J|cnpj',
'inscricao_estadual'=> 'required_if:tipo,J',

Next, I’m wearing this required if, and when the request comes with type 'J' it validates in Cpf, how to solve?

  • What exactly happens is perhaps the second validation he performs!

  • but there is a way for required if to extend to Cpf. Because when type is 'J' I don’t want it to validate Cpf.

1 answer

3

The required_if can also be used this way: required_if:<field>,<comparador>,<valor>

Example:

'field1' => 'required|numeric',
'field2' => 'required_if:field1,==,2|string'

In your case, I believe that a condition concatenated to string could solve, example:

Valitador::make($request->all(), [
  'tipo'              => 'required',
  'cpf'               => ($request['tipo']=='F' ? 'required|cpf' : 'nullable'),
  'rg'                => 'required_if:tipo,==,F',
  'cnpj'              => ($request['tipo']=='J' ? 'required|cnpj' : 'nullable'),
  'inscricao_estadual'=> 'required_if:tipo,==,J'
]);

Browser other questions tagged

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