Manas
Manas

Reputation: 3330

how to validate one of the form data which is an array?

I have a form with these inputs: name, height , weight and mobilenumbers[](this is an array) for example: mobilenumbers

[12345678,88665544,45456574,33669988]

The user can dynamically add more fields of "mobilenumbers". I need to validate the array of "mobilenumbers". How do i do that? Laravel documentation is quite confusing. whether i need to write custom validation in AppServiceProvider or can i simply validate each data in the array? in laravel 5.4 documentation it says something like:

$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);

but in my case my array is simply mobilenumbers[], how do i do that?

Thanks a lot in advance

Upvotes: 1

Views: 237

Answers (3)

Manas
Manas

Reputation: 3330

I figured out the answer.

 public function create(Request $request){

     $validation = $this->validate($request, [

         'name' => 'Required',
         'mobilenumbers.*' => 'phone:US', //adding.* identifies it as an array
         'height' => 'required',  
         'weight' => 'Required',


    ]);

and the phone:US that i am using here is anoter package which helps you check for the mobilenumber format is in speficied country tpe or not. Like im using US to check if all the entered mobile numbers are US based numbers. you can check out that library here for laravel: https://github.com/Propaganistas/Laravel-Phone

Upvotes: 1

Almazik G
Almazik G

Reputation: 1077

what is that that you're trying to validate against? If you simply want to check that the array has at least some values you can do

public function rules()
{
    return [
        'mobilenumbers' => 'min:1',
    ];
}

Upvotes: 2

Shane Henry
Shane Henry

Reputation: 318

$validator = Validator::make(
    ['person.*.mobilenumbers.*' => 'required|numeric|min:1'
);

Upvotes: 1

Related Questions