Sergej Fomin
Sergej Fomin

Reputation: 2002

Laravel Custom Validation Rules should be lowercase?

I have model, and it has several field names, and 'lastName' is among them.

In my FormRequest file, I have rules and messages for this field:

$rules = ['lastName.*' => 'lastName_fail: index'];
$messages = ['lastName.*lastName_fail' => This lastName has different value in DB!'];

When I am submitting a form, filling the 'lastName' field with intentionally 'wrong' value, it doesn't pass validation, and returns error message:

validation.last_name_fail

(which is not what's in $messages).

But when I change $rules and $messages to:

$rules = ['lastName.*' => 'lastname_fail: index'];
$messages = ['lastName.*lastname_fail' => This lastName has different value in DB!'];

(so the actual "rule" is now lowercase "lastname_fail"), it outputs what i want:

This lastName has different value in DB!

from this I may conclude that Laravel's validation rule name may be only lowercase.

Is it declared anywhere in documentation?

If so, maybe it helps someone.

Upvotes: 1

Views: 7398

Answers (2)

MarcoPa84
MarcoPa84

Reputation: 21

Simply parse $request[data] before Validator

use Illuminate\Support\Str;
    
    $request['name_it'] = Str::lower($request['name_it']);
    $request['name_en'] = Str::lower($request['name_en']);
                
    $validator = Validator::make($request->all(), [
    'name_it' => ['required', 'string', 'max:255', 'unique:categories'],
    'name_en' => ['required', 'string', 'max:255', 'unique:categories'],
    ]);
    if ($validator->fails()) {
        return redirect()
    ->back()->withErrors($validator)
    ->withInput();
    }

Upvotes: 1

Zayn Ali
Zayn Ali

Reputation: 4925

It is not mentioned in the documentation. However, there is a naming pattern for both validation rule method name and rule name.

Rule Method Name:

It must have validate prefix and the rest of it must be in Camel Case.

Rule Name:

It will be in lowercase without the validate prefix and each word will be separated by an underscore.


So if you want to add alpha_dash_spaces validation rule then the corresponding method will be named validateAlphaDashSpaces().

Upvotes: 1

Related Questions