user3155378
user3155378

Reputation: 21

How to use custom validation attributes on an array of inputs

I'm using Laravel to build a form that contains an array of inputs and I’m having difficulty in showing the translated attribute name when a validation error occurs. For simplicity sake I will post a simple example of my problem.

Form inside the view:

<form method="POST" action="{{ route('photo.store') }}" accept-charset="UTF-8" role="form">
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div class="row">
    <div class="col-lg-12">
        <div class="form-group{{ $errors->has('testfield') ? ' has-error' : '' }}">
            <label class="control-label"
                   for="testfield">{{ trans('validation.attributes.testfield') }}</label>
            <input class="form-control" name="testfield" type="text" id="testfield"
                   value="{{ old('testfield') }}">
            @if ($errors->has('testfield'))
                <p class="help-block">{{ $errors->first('testfield') }}</p>
            @endif
        </div>
    </div>
    <div class="col-lg-12">
        <div class="form-group{{ $errors->has('testfieldarray.0') ? ' has-error' : '' }}">
            <label class="control-label"
                   for="testfieldarray-0">{{ trans('validation.attributes.testfieldarray') }}</label>
            <input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-0"
                   value="{{ old('testfieldarray.0') }}">
            @if ($errors->has('testfieldarray.0'))
                <p class="help-block">{{ $errors->first('testfieldarray.0') }}</p>
            @endif
        </div>
    </div>
    <div class="col-lg-12">
        <div class="form-group{{ $errors->has('testfieldarray.1') ? ' has-error' : '' }}">
            <label class="control-label"
                   for="testfieldarray-1">{{ trans('validation.attributes.testfieldarray') }}</label>
            <input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-1"
                   value="{{ old('testfieldarray.1') }}">
            @if ($errors->has('testfieldarray.1'))
                <p class="help-block">{{ $errors->first('testfieldarray.1') }}</p>
            @endif
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <input class="btn btn-primary" type="submit" value="Gravar">
    </div>
</div>

Rules function in the form request:

public function rules() {
    $rules = [
        'testfield' => array('required'),
    ];

    foreach ($this->request->get('testfieldarray') as $key => $val) {
        $rules['testfieldarray.' . $key] = array('required');
    }

    return $rules;
}

lang/en/validation.php

'attributes' => [
    'testfield' => 'Test Field',
    'testfieldarray' => 'Test Field Array',
],

The validation is performed correctly, as do the error messages. The only problem in the error messages is the name of the attribute displayed. In both array inputs, the attribute name inserted in the message is 'testfieldarray.0' and 'testfieldarray.1' instead of 'Test Field Array'. I already tried to add on the language file 'testfieldarray.0' => 'Test Field Array', 'testfieldarray.1' => 'Test Field Array', but the messages remain unchanged. Is there a way to pass the attribute names correctly?

Upvotes: 2

Views: 4322

Answers (3)

Abdelatif Ben-ichou
Abdelatif Ben-ichou

Reputation: 31

1-if you split the validation in file request then add the method attributes and set the value of each key like this :

 public function attributes()
    {
        return [
          'name'=>'title',
         

        ];
    }

2- but if don't split the validation of the request then you just need to make variable attributes and pass the value of items like this :

$rules = [
  'account_number' => ['required','digits:10','max:10','unique:bank_details']
];
$messages = [];
$attributes = [
    'account_number' => 'Mobile number',
];
$request->validate($rules,$messages,$attributes);
// OR
$validator = Validator::make($request->all(), $rules, $messages, $attributes);

Upvotes: 1

Majbah Habib
Majbah Habib

Reputation: 8558

Just see the example to add custom rules for integer type value check of array

Open the file

/resources/lang/en/validation.php

Then add the custom message.

// add it before "accepted" message.
'numericarray'         => 'The :attribute must be numeric array value.',

Again Open another file to add custom validation rules.

/app/Providers/AppServiceProvider.php

So, add the custom validation code in the boot function.

public function boot()
{
    $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
    {
        foreach ($value as $v) {
            if (!is_int($v)) {
                return false;
            }
        }
        return true;
    });
}

Now you can use the numericarray for integer type value check of array.

$this->validate($request, [
            'input_filed_1' => 'required',
            'input_filed_2' => 'numericarray'
        ]);

----------- Best of Luck --------------

Upvotes: 1

Carlos Arauz
Carlos Arauz

Reputation: 805

Use custom error messages inside your parent method....

public function <metod>(Request $request) {
    $rules = [
        'testfield' => 'required'
    ];
    $messages = [];

    foreach ($request->input('testfieldarray') as $key => $val) {
        $rules['testfieldarray.' . $key] = 'required';
        $messages['testfieldarray.' . $key . '.required'] = 'Test field '.$key.' is required';
    }

    $validator = Validator::make($request->all(), $rules,$messages);
        if ($validator->fails()) {
            $request->flash();
            return redirect()
                ->back()
                ->withInput()
                ->withErrors($validator);
        }
    }
}

Upvotes: 0

Related Questions