AdRock
2 years ago

Custom validation required in other field in whitelist array

Posted 2 years ago by AdRock

I am really struggling getting some custom validation to work and need help!!

I am looking for a rule similar to required_if but instead of looking for a value which equals something, I want to have a value which is in an whitelist array.

$whitelist = array(
    'red',
    'yellow',
    'green',
    'blue',
    'black'
);

here is the rule I've created

$rules = array(
    'colour' => 'colour_required:' . $product['colour'] . ',' .implode(',', $whitelist),
);

and in App\Providers\AppServiceProvider.php I've added a custom validation function

Validator::extend('colour_required', function ($attribute, $value, $parameters, $validator) {
    $colour = $parameters[0];
    $whitelist = explode(',', $parameters[1]); 
    
    return !in_array($colour, $whitelist);
}, 'ffghgjghjg');

it never works. I always get an validation message saying the colour is required even if it's in the whitelist

Please sign in or create an account to participate in this conversation.