Home > other >  Laravel Validator - Check if contain error key?
Laravel Validator - Check if contain error key?

Time:09-17

I have a validator like this,

$validator = Validator::make($request->query(),
    [
        'size'   => 'required|numeric|max:' . (100 * 1024 * 1024)
    ],
    [ 
        'size.required'   => 'param size is required',
        'size.numeric'    => 'param size should be numberic',
        'size.max'        => 'param size is over size'
    ]);

and now I want to check the $validator has error size.required

$messages = $validator->errors();
if ($messages->has('size.required')) {
    // do something...
} else if ($messages->has('size.numeric')) {
    // do something...
}

So is there a way to implement it?

Thanks for any idea.

CodePudding user response:

Not a good solution but you can check if error message contains a keyword:

use Illuminate\Support\Str;
 
if( Str::contains($messages->first('size'), 'required')){
    // do something..
}

CodePudding user response:

I think you are looking for failed method in Validation class

$sizeArray = [
        'required' => '', //Required Validation Will Fail
        'numeric' => 'string', //Numeric Validation will fail
        'max' => (100 * 1024 * 1024 * 10),//max validation will fail
        'success_one' => '1234',
        'success_two' => 1234
    ];

    $validator = Validator::make(
        [
            'size' => $sizeArray['numeric']
        ],
        [
            'size'   => 'required|numeric|max:' . (100 * 1024 * 1024)
        ],
        [
            'size.required'   => 'param size is required test manoj',
            'size.numeric'    => 'param size should be numberic',
            'size.max'        => 'param size is over size'
        ]
    );

    $validator->errors();//Don't Remove this line
    $failedValidation = collect($validator->failed())->map(function ($parameterFailedRules, $parameter) {
        return array_change_key_case($parameterFailedRules, CASE_LOWER);
    });

    if (Arr::has($failedValidation, 'size.required')) {
        dd('required Validation Failed');
    }else if(Arr::has($failedValidation, 'size.numeric')){
        dd('numeric Validation Failed');
    } else if (Arr::has($failedValidation, 'size.max')) {
        dd('max Validation Failed');
    }else{
        dd('All Validation Passed');
    }

Please Change the input value of size to change the error message.

Currently it will show .

"numeric Validation Failed"

  • Related