2

I've custom validation code:

$this->validate($request, [
    'array' => 'required|array|max:100',
    'array.*' => 'required|string|distinct|min:3'
], [
    'array.max' => 'Array can't have more :max items',
]);

Here how I can add cusom message with array items rule?

For example: 'array.item.min' => 'Array items length can't be greater :min charackters'

Example laravel default validation error message for array items:

{
  message: "The given data was invalid."
}

errors: {
  array.3: ["The array.3 must be at least 3 characters."]
}

array.3: ["The array.3 must be at least 3 characters."]

0: "The array.3 must be at least 3 characters."
message: "The given data was invalid."

How I can replace this validation message with my single message for array items?

3
  • can you provide more code so i can understand better Commented Oct 23, 2018 at 9:05
  • I'm not sure, can you try array.*.min? Commented Oct 23, 2018 at 9:11
  • @aceraven777, it's not working. Commented Oct 23, 2018 at 9:13

1 Answer 1

3

You can try adding custom messages on each element when the form is submitted. Here's the sample code

$customMessages['array.max'] = "Array can't have more :max items";

foreach ($request->get('array') as $key => $value) {
    $customMessages['array.' . $key . '.min'] = "Array items length can't be greater :min characters";
}

$this->validate($request, [
    'array' => 'required|array|max:100',
    'array.*' => 'required|string|distinct|min:3'
], $customMessages);

If you want to show the error in your view, you can do this:

@if ($errors->has('array.0'))
    {{ $errors->first('array.0') }}
@endif

If you have foreach in the view

@if ($errors->has('array.'.$index))
    {{ $errors->first('array.'.$index) }}
@endif
Sign up to request clarification or add additional context in comments.

3 Comments

How can I show then generated error message in your mean? @aceraven777
For example I will return error message and use it with javascript. Example generated message in js: skills.2: Array(1). Here array name is skills.2. Error with 2 item of array. Can you say your mean about showing error messages?
@aceraven77 you saved me.i wish i can like this answer a thousand times

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.