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);
}
3

2 Answers 2

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'
      ];
}
Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

I add new $validator variable for each input?
edited to answer specific to your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.