'Lumen validation rules not working for optional fields
I'm trying to validate this request payloads:
Case 1:
{
"products": [],
"suppliers": ["supplier hash"]
}
Case 2:
{
"products": [],
"withinDeliveryRange": {
"distance": 50,
"postalCode": "85012"
},
}
Case 3:
{
"products": [],
"suppliers": ["supplier hash"],
"withinDeliveryRange": {
"distance": 50,
"postalCode": "85012"
},
}
Case 4:
{
"products": [],
"suppliers": ["supplier hash"],
"withinDeliveryRange": {
"distance": 50,
"postalCode": "85012"
},
}
This my validation rules:
$this->validate(
$_request,
[
'products' => 'array|nullable',
'suppliers' => 'required_unless:withinDeliveryRange,null|array|nullable',
'withinDeliveryRange' => 'required_unless:suppliers,null|array:distance,postalCode|nullable',
]
);
I'm expecting all cases to pass the validation, except the case 4 when we don't provide any of them, however:
- case 1: passes
- case 2: fails
- case 3: passes
- case 4: fails
The case 2 fails and the rule for withinDeliveryRange should work as for suppliers does, it's kind weird too because sometimes this case 2 passes but most of the times it fails.
Error message:
{"suppliers":["The suppliers field is required unless within delivery range is in null."]}
Are my rules correct? what should I change or maybe another rules fits better for this scenario.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
