Chron's avatar

Validations & Custom Rule

Is there a way to prevent the Custom Rule from running when the prior rules failed?

$userInput = [
    'offset' => [
        'a' => "abcd",
        'b' => "abcd,
    ],
	'photo' => $file
];

in FormRequest

//...
['photo' => ['image']],
['offset' => ['bail', 'array:x,y', new OffsetCheck($this->photo)]],
['offset.*' => ['numeric'],

OffsetCheck uses the values of x and y but got a and b so it should throw an error and stop before going to the custom rule but I still get Undefined array key "x" from OffsetCheck. Do I need to repeat the set of validations inside the custom rule?

0 likes
8 replies
Chron's avatar

I just want to be specific. That would also accept arrays with other keys as long as x,y exists

Glukinho's avatar

Is OffsetCheck a custom rule class with implements DataAwareRule, ValidationRule? Is it in App\Rules namespace? Can you show the code?

It seems wrong you create an object and pass some data in constructor; custom rule object should get request data internally with setData() method: https://laravel.com/docs/12.x/validation#using-rule-objects (see Accessing additional data)

With new OffsetCheck($data) you force in-class logic to execute immediately, while it should be applied or not applied conditionally by validator.

Chron's avatar

Oh yeah, I refactored it to use setData and DataAwareRule

//OffsetCheck

public function validate(string $attribute, mixed $value, Closure $fail): void {
	[$w, $h] = getimagesize($this->data['photo']);
	if($this->data['offset']['x'] > $w || $this->data['offset']['y'] > $h) {
		$fail('Offset invalid');
	}
}
'offset' => ['bail', 'array:x,y', new OffsetCheck],

But it still giving me Undefined array key "x" when it should stop on the array:x,y since it has a bail and it failed the validation.

Glukinho's avatar

Try this:

'offset' => ['bail', 'array', 'size:2', 'required_array_keys:x,y', new OffsetCheck],

For unknown reason array:x,y rule gives me strange error "field must be array" (which it definitely is) while simple array is fine.

1 like
Chron's avatar
Chron
OP
Best Answer
Level 6

Yeah that's what array:keys throws when it is invalid.

I just combined those two

['offset' => ['bail', 'array:x,y', 'required_array_keys:x,y', new OffsetCheck]],

Please or to participate in this conversation.