Check field only if it has any Laravel value

Asked

Viewed 419 times

-1

Guys I have a user registration system, in this system has a CPF field, where I use a class to validate it, but the field is not mandatory, and all the classes I tried to validate Cpf, validates even if the field is empty because you understand that the empty field does not have a valid Cpf format. So my idea, not to mess with the class, is to check the Cpf field if it came empty/null, so just do the check.

I use it this way:

    $rules = [
        'email' => 'required|email|min:3|max:60|unique:users,email,
        'name'     => 'required|min:3|max:70',
        'cpf'      => 'cpf',

    ];

    $this->validate($request, $rules);

I tried to use the required_if but I could not form the logica. If anyone can help I really appreciate.

1 answer

0


Of the documentation of Laravel.

By default, Laravel includes the Trimstrings and Convertemptystringstonull middleware in your application’s global middleware stack. These middleware are Listed in the stack by the Http Kernel class app. Because of this, you will often need to mark your "optional" request Fields as nullable if you do not want the Validator to consider null values as invalid.

$rules = [
    'email' => 'required|email|min:3|max:60|unique:users,email',
    'name'     => 'required|min:3|max:70',
    'cpf'      => 'nullable|cpf',

];

$this->validate($request, $rules);

In some scenarios where input is not sent together with the request, you can use the validator sometimes

$rules = [
    'email' => 'required|email|min:3|max:60|unique:users,email',
    'name'     => 'required|min:3|max:70',
    'cpf'      => 'sometimes|required|cpf',

];

$this->validate($request, $rules);
  • This is Vinicius, thank you very much for the answer. I’m even using a class you created to validate Cpf, I downloaded it from git. I will try to do as you put it, then put the result.

  • thanks, thank you very much, solved my problem. Congratulations and success.

Browser other questions tagged

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