Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 form validation with input values that are arrays

All of my form fields have brackets in their names in order to group them by parent and to identify them as recurring elements, example: fieldName_01[0][0]. Of course, this makes regular use of Laravel's Validator class impossible, as it throws an error referencing that it is not expecting an array. This naming convention is common practice, so this can't be a rare issue.

I've see a couple other similar questions (HERE and HERE), but I can't seem to make sense of them (Laravel noob), or I just don't know how/where to implement the solutions. In this answer, where would I create this extended class? How do I tell Laravel to include it in my project?

Example of my elements:

<div class="form-group col-sm-4'}}">
    {{ Form::label('fieldName_01[0][0]', 'My Element', array('class'=>'col-sm-3'))}}
    <div class="col-sm-7 col-md-6 recurringField">
    {{ Form::text('fieldName_01[0][0]', null, array(
        'class'=>'form-control input-md',
        'placeholder'=>'My Element',
        'data-element-code' => '',
        'data-recur-group' => 'fieldName_01',
        'id'=>'fieldName_01[0][0]',
        'data-fkey' => '0',
        'data-pkey' => '0'
    )) }}
    </div>
</div>

Example of my rule:

'fieldName_01'=>'required|alpha_num|between:2,255'

Example of how I'm calling the validator:

$input = Input::all();
$validator = Validator::make($input, $this->rules);
like image 387
jreed121 Avatar asked Jan 10 '23 18:01

jreed121


1 Answers

As per the documentation:

When working on forms with "array" inputs, you may use dot notation to access the arrays:

(warning untested code)

If you have something like user[first_name] then:

'user.first_name' => 'required|between:2,28'

You can handle any errors with:

$errors->first('user.first_name');

So with your problem, you can validate fieldName_01[0][0] like:

'fieldName_01.0.0' => 'required|alpha_num|between:2,255'
like image 89
majidarif Avatar answered Jan 31 '23 08:01

majidarif