mardi 17 novembre 2020

Custom Validator Rules in Laravel Return always message

I have a problem that I can't find a solution, in reality 2 problems.

The first problem is the following, I made a custom validation rule to validate the "NIF" (identity used in Portugal), until this point everything is working, the validation rule is working, the problem is the message that is returning, the message is always "The given data was invalid." but "Invalid NIF" should appear.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NifValidator implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $ignoreFirst = true;
        $nif = trim($value);
        \Log::info("Valida Rules NIF: " . $nif);
        //Verificamos se é numérico e tem comprimento 9
        if (!is_numeric($nif) || strlen($nif) != 9) {
            return false;
        } else {
            $nifSplit = str_split($nif);
            //O primeiro digíto tem de ser 1, 2, 5, 6, 8 ou 9
            //Ou não, se optarmos por ignorar esta "regra"
            if (
                in_array($nifSplit[0], [1, 2, 5, 6, 8, 9])
                ||
                $ignoreFirst
            ) {
                //Calculamos o dígito de controlo
                $checkDigit = 0;
                for ($i = 0; $i < 8; $i++) {
                    $checkDigit += $nifSplit[$i] * (10 - $i - 1);
                }
                $checkDigit = 11 - ($checkDigit % 11);
                //Se der 10 então o dígito de controlo tem de ser 0
                if ($checkDigit >= 10) {
                    $checkDigit = 0;
                }

                //Comparamos com o último dígito
                if ($checkDigit == $nifSplit[8]) {
                    \Log::info("VALIDA NIF  TRUE");
                    return true;
                } else {
                    \Log::info("VALIDA NIF  False");
                    return false;
                }
            } else {
                \Log::info("VALIDA NIF  false");
                return false;
            }
        }
    }

    public function validate($attribute, $value, $params)
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute inválido';
    }
}

My AppServiceProvider.php

<?php

namespace App\Providers;

use Hyn\Tenancy\Environment;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $env = app(Environment::class);

        if ($fqdn = optional($env->hostname())->fqdn) {
            config(['database.default' => 'tenant']);
        }

        // money format
        Str::macro('money', function ($price) {
            return number_format($price, 2, ',', '.');
        });

        \Validator::extend('nifvalidator', '\App\Rules\NifValidator@validate');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

My Controller

<?php

namespace App\Http\Controllers\Auth;

use App\Authentication\Register;
use App\Http\Controllers\Controller;
use Exception;

class RegisterController extends Controller
{
    use \App\Traits\Helpers\ResponseJSON;

    public function create()
    {
        try {
            $payload = request()->all();

            $rules = [
                'nif' => 'required',
                'name' => 'required',
                'email' => 'required|email',
                'password' => [
                    'required',
                    'string',
                    'min:8', // must be at least 8 characters in length
                    'regex:/[A-Za-z]/', // must contain at least one uppercase letter
                    'regex:/[0-9]/', // must contain at least one digit
                ],
                'country' => 'required',
            ];

            $messages = [
                'password.regex' => 'A password precisa ter no minimo 1 letra e 1 número',
            ];

            //portugal
            if (176 == $payload['country']) {
                // if (!Cliente::validaNif($payload['nif'])) {
                //     throw new Exception("register.nif_invalid");
                // }
                $rules['nif'] = "nifvalidator";
            }

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

            
            return $this->responseJSON([], 'register.register_success');
        } catch (\Illuminate\Validation\ValidationException $validExcept) {
            return $this->responseJSON([], $validExcept->getMessage(), 401);
        } catch (Exception $except) {            
            return $this->responseJSON([], $except->getMessage(), 401);
        }
    }
}

The second problem is that if I noticed the controller I did a regex validation in the password field to identify if there is a letter or a number, I also customized the message that would appear in the regex field, but the message that returns is always the same "The given data was invalid.

To be honest, I don't know what to do anymore, everything I found on the internet I tried and it didn't work.

I really appreciate the help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire