How to validate request value when it should be string or array both valid?
'val' => 'bail|required|string'
'val' => 'bail|required|array'
What would be the the validation expression?
The most basic validation, it's a set of conditions that check whether the structure is the expected one. const validate = (data: ExampleType) => { if (! data. pets) return false; // perform more checks return true; }; const getBiped = async () => { const data = await fetchData(); console.
I don't think there is a way to achieve it using the validation rules out of the box. You will need to use Custom Validation Rules to achieve this:
In AppServiceProvider
's boot
method, add in
public function boot()
{
Validator::extend('string_or_array', function ($attribute, $value, $parameters, $validator) {
return is_string($value) || is_array($value);
});
}
Then you can start using it:
'val' => 'bail|required|string_or_array'
Optionally you can set the custom validation error messages, or using a custom validation class to achieve it. Check out the doc link above for more information.
The solution provided by @lionel-chan is most elegant way but you can also do it by checking type of the variable in order to add the appropriate rule as:
$string_or_array_rule = is_array($inputs['val']) ? 'array' : 'string'
"val" => "bail|required|{$string_or_array_rule}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With