Home > Back-end >  How to customize validation messages using Laravel?
How to customize validation messages using Laravel?

Time:03-31


    public function UserCheck(Request $request)
    {
        $Code0 = array("code" => 0, "message" => "Username is valid");
        $Code1 = array("errors" => array(array("code" => 1, "message" => "A valid username is required.", "userFacingMessage" => "Something went wrong")));
        $Code2 = array("code" => 2, "message" => "Username not appropriate for ". config('app.name'));
        $Code3 = array("code" => 3, "message" => "Usernames can be 3 to 20 characters long");

        $validate = $request->validate([
            'username' => ['required', 'string', 'min:3', 'max:20', 'unique:users', 'regex:/^[a-zA-Z0-9_]*$/'],
        ]);

    } 

How would I go making this API show custom error messages if validation fails? I read this https://laravel.com/docs/9.x/validation#quick-writing-the-validation-logic but it doesn't help

Also, the regex, is there any way where It can only be in the middle and no more than 1?

I have tried reading the docs googling about validating queries nothing helped I expect the API to return "{"code":0,"message":"Username is valid"}" if validation passes OR if it fails return one of the error Example: Username under 3 Characters then return "{"code":3,"message":"Usernames can be 3 to 20 characters long"}"

Please help me

CodePudding user response:

You can customize your validation messages, check laravel documentation here.

Your code should look like something like this:

$messages = [
    'min' => json_encode(['code'=> 3, 'message' => 'Username must be at least 3 characters']),
];

$validator = Validator::make($request->all(), [
    'username' =>
        [
            'required',
            'string',
            'min:3',
            'max:20',
            'unique:users',
            'regex:/^[a-zA-Z0-9_]*$/'
        ]
], $messages);

if ($validator->fails()) {
    return response()->json($validator->messages(), 422);
}else{
    return response()->json(["code" => 0, "message" => "Username is valid"]);
}

Here is customized only message for min rule, but you can do the same for all rules.

  • Related