3

These arrays I put into Laravel Validator as arguments:

['item.*' => 'string'] // rules

['item.*.string' => 'Item number (index) is not string'] // messages

I want to have index number in validation message. Code above is just for demonstration and does not work. How to do this?

2 Answers 2

8

Try this or use this one

    'name' : [ { 'value' : 'raju' } , { 'value' : 'rani'} ]       

and validate it by

    'name.*' or 'name.*.value' => 'required|string|min:5'       

The message will be

    'name.*.required' => 'The :attribute is required'       
    'name.*.value.required' => 'The :attribute is required'      

I think it will help to you..

Try this one,

public function messages()
{
    $messages = [];
    foreach ($this->request->get('name') as $key => $value){
        $messages['name.'. $key .'.required'] = 'The item '. $key .'  is not string';
    }
    return $messages;
}
Sign up to request clarification or add additional context in comments.

5 Comments

well I need index to be displayed in message. This will display just attribute name.
@Fusion I think, The :attribute place will give name.0, name.1 and etc, So, it is not enough for require.?
@Fusion { "name.0": [ "item number name.0 is not a string." ] } this is my alter output for your knowledge.
Answer is helpful, however i would like to have something like: 'name.*.value.required' => 'The error is located at :index' ( notice there is no attribute mentioned). It is possible to parse message for index, however I find it cumbersome.
@Fusion please use the message function style and it will return the index value.
1

In new version of Laravel you can try:

'item.*.string' => 'Item number :position is not string'

:position will be replaced with human readable number, for example 0 index converting to 1.

Comments

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.