Search code examples
phplaravelvalidationrequest

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?


Solution

  • 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.