I have an array which I would like to be validated. The post json payload looks like this
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : {
"phone" : "0466144569",
"email" : "test@test.com",
"country" : "US",
"language" : "en",
"name" : "rockstar"
},
"user" : {
"username" : "rockstar",
"password" : "rockstarpassword",
"consent" : {
"gdpr": "true",
"version": "consent_doc_2009"
}
}
}
The issue is that, this payload can change in 4 different scenarios.
1) The whole payload exists. Just like the above example.
2) Where organization
is missing.
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : null
"user" : {
"username" : "rockstar",
"password" : "rockstarpassword",
"consent" : {
"gdpr": "true",
"version": "consent_doc_2009"
}
}
}
3) Where user
is missing.
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : {
"phone" : "0466144569",
"email" : "test@test.com",
"country" : "US",
"language" : "en",
"name" : "rockstar"
},
"user" : null
}
}
4) Where organization
and user
is both missing.
{
"guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
"organization" : null,
"user" : null
}
I have a laravel request class that validates this.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class organizationCreation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'guid' => 'required|string',
'organization.name' => 'required_with:organisation|string|min:3',
'organization.phone' => 'required_with:organisation|regex:/^([0-9\s\-\+\(\)]*)$/|max:20',
'organization.country' => 'required_with:organisation|max:2',
'organization.language' => 'required_with:organisation|max:2',
'organization.email' => 'required_with:organisation|string|max:255',
'user.username' => 'required_with:user|string|max:255',
'user.password' => 'required_with:user',
'user.consent.gdpr' => 'required_with:user|boolean',
'user.consent.version' => 'required_with:user|string|max:255',
];
}
}
I tried the above validation, and used required_with, but then it looks like the validations fail, and I am not sure how to go forward with this validation that has 4 different rules.
I can separately validate them by checking the payload with if
and not write code for it but I would like to do them all at once.