In Laravel Livewire I added a custom youtube video validation rule. It works very well, the problem is that I need it to be nullable and if I add in the validate nullable it gives me an error and I can't find how to solve this problem.
Input:
<input wire:model="video" class="form-control" type="text" placeholder="Url youtube">
Rule:
public function passes($attribute, $value)
{
return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$value);
}
Validate:
'video' => 'nullable', new RuleYoutube,
Removing nullable works fine, but the field is not required. And with the nullable property I get the following error:
No property found for validation: [0]
Any suggestion? Thank you very much for spending time in my consultation
The way I solved this issue was to utilise Livewire's validateOnly
method with an invokable validation Rule.
public function updated($propertyName)
{
if($propertyName == 'enquiry.contact_email'){
$this->validateOnly('enquiry.contact_email', [
'enquiry.contact_email' => [new DelimitedEmail, 'required']
]);
}
}
Invokable rule:
php artisan make:rule DelimitedEmail --invokable
Code:
class DelimitedEmail implements InvokableRule
{
public function __invoke($attribute, $value, $fail)
{
$func = function(string $value): string {
return trim($value);
};
if(str_contains($value, ',')) {
$emails = array_map($func,explode(',',$value));
foreach($emails as $email) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) $fail('This field has an invalid email address.');
}
} else {
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) $fail('That is an invalid email address.');
}
}
}