How to use custom validation and sometimes rules

Hi

How do i use custom validation rules with livewire?
I have a field where the validation depends on the content of this field.
When content of this field begins with the char A the validation Rule A should be used.
When i use a request class and then use the Validator Instance and add those rules like this:

protected function getValidatorInstance() {
$validator = parent::getValidatorInstance();
$validator->sometimes(‘type’, [new TypeA], function ($input) {
if ($type== “A”) {
return true;
}
return false;
});
return $validator;
}

How do i add my custom Rule in livewire?
I cant add an object instance to the rules constant.

How do i proceed?

Thanks Tobi

You can inject your custom validation directly

...
[
 'title' => ['required', 'string', function ($attribute, $value, $fail) use ($variable) {
            // your logic

            // if fails you can throw and error message
                $fail('error message');
       }
]
...
1 Like

Hello, yeah i did realize that you can use the function handler (public function rules()) as well.
The static constant doesnt accept functions…

Tobi