Validation of array form fields in laravel 4 error -


how can validate form fields arrays? take @ following code

userphone model:

 public static $rules= array(     'phonenumber'=>'required|numeric',     'isprimary'=>'in:0,1' ) ........... 

usercontroller:

$validation = userphone::validate(input::only('phonenumber')));       if($validation->passes())       {          $allinputs = input::only('phonenumber','tid');          $loopsize = sizeof($allinputs);           for($i=0;$i<$loopsize;$i++)          {           $phone = userphone::find($allinputs['tid'][$i]);          $phone->phonenumber = $allinputs['phonenumber'][$i];          $phone->save();          }       return redirect::to('myprofile')->with('message','update ok');    }   else   {      return redirect::to('editphone')->witherrors($validation);    }   } 

the $validation comes basemodel extends eloquent.

in view:

 <?php $counter=1; ?>           @foreach($phones $thephone)             <section class="col col-12">               <label class="label">phone number {{$counter++}}</label>               <label class="input">               <i class="icon-append icon-phone"></i>                  {{form::text('phonenumber[]',$thephone->phonenumber)}}                  {{form::hidden('tid[]',$thephone->id)}}               </label>             </section>           @endforeach 

everything working fine , phone numbers want in update form, cannot update model because validation fails message "phonenumber must number".

i know there not simple solution validating array form fields , tried extend validator class no success.

how can validate kind of fields?

here's solution use:

usage

simply transform usual rules prefixing each. example:

'names' => 'required|array|each:exists,users,name' 

note each rule assumes field array, don't forget use array rule before shown here.

error messages

error messages automatically calculated singular form (using laravel's str_singular() helper) of field. in previous example, attribute name.

nested arrays

this method works out of box nested arrays of depth in dot notation. example, works:

'members.names' => 'required|array|each:exists,users,name' 

again, attribute used error messages here name.

custom rules

this method supports of custom rules out of box.

implementation

1. extend validator class

class extendedvalidator extends illuminate\validation\validator {      public function validateeach($attribute, $value, $parameters)     {         // transform each rule         // example, `each:exists,users,name` becomes `exists:users,name`         $rulename = array_shift($parameters);         $rule = $rulename.(count($parameters) > 0 ? ':'.implode(',', $parameters) : '');          foreach ($value $arraykey => $arrayvalue)         {             $this->validate($attribute.'.'.$arraykey, $rule);         }          // return true, since errors occur individual elements.         return true;     }      protected function getattribute($attribute)     {         // second last segment in singular form arrays.         // example, `group.names.0` becomes `name`.         if (str_contains($attribute, '.'))         {             $segments = explode('.', $attribute);              $attribute = str_singular($segments[count($segments) - 2]);         }          return parent::getattribute($attribute);     } } 

2. register validator extension

anywhere in usual bootstrap locations, add following code:

validator::resolver(function($translator, $data, $rules, $messages) {     return new extendedvalidator($translator, $data, $rules, $messages); }); 

and that's it! enjoy!

bonus: size rules arrays

as comment pointed out, there's seems no easy way validate array sizes. however, laravel documentation lacking size rules: doesn't mention can count array elements. means you're allowed use size, min, max , between rules count array elements.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -