0

Greeting, this is my code and I need to make custom error messages for every rule

$validator = Validator::make($request->all(), [
        'name' => 'required|min:3|max:100',
        'phone' => 'required',
        'date' => 'required',
        'address' => 'required|min:3|max:100',
        'test' => 'required|min:3|max:100',
    ]);

if ($validator->fails()) {
    $errors = $validator->errors();
    return response()->json($errors);
}
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Osama Amr
  • 21
  • 2
  • 11
  • 1
    Ref :https://laravel.com/docs/8.x/validation#manual-customizing-the-error-messages – John Lobo Dec 12 '21 at 08:19
  • Does this answer your question? [Custom Laravel validation messages](https://stackoverflow.com/questions/45007905/custom-laravel-validation-messages) – John Lobo Dec 12 '21 at 08:21
  • Laravel documentation is the greatest source you can have , first try to check there and read it . https://laravel.com/docs/8.x/validation#customizing-the-error-messages – John Dec 12 '21 at 11:17

2 Answers2

1

you can create your own custom validation messages in two ways:

1- in resources/lang/en/validation.php you can change the validation message for every rule

2- you can pass your custom message for each validation like this:

$validator = Validator::make($input, $rules, $messages = [
    'required' => 'The :attribute field is required.',
]);

you can check here for more information

specific to your question:

$messages = [
   'required' => 'The :attribute field is required.',
   'min' => ':attribute must be more than 3 chars, less than 100'
]
$validator = Validator::make($request->all(), [
        'name' => 'required|min:3|max:100',
        'phone' => 'required',
        'date' => 'required',
        'address' => 'required|min:3|max:100',
        'test' => 'required|min:3|max:100',
    ], $messages);
Mah Es
  • 620
  • 4
  • 6
1

Its better to create a separate request for validation purpose

public function rules(): array
{
        return [
        'name' => 'required|min:3|max:100',
        'phone' => 'required',
        'date' => 'required',
        'address' => 'required|min:3|max:100',
        'test' => 'required|min:3|max:100',
    ]
}

public function messages(): array
{
      return [
                'name' => 'Please enter name'
      ];
}
Kamran Khalid
  • 260
  • 1
  • 7