Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation value having two possible types

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?

like image 514
Jocky Doe Avatar asked Nov 13 '16 13:11

Jocky Doe


People also ask

How do I validate typescript?

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.


2 Answers

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.

like image 133
Lionel Chan Avatar answered Sep 30 '22 18:09

Lionel Chan


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}"
like image 32
Amit Gupta Avatar answered Sep 30 '22 17:09

Amit Gupta