Dear I need to validate that a Youtube url is entered in an input
<input wire:model="video" class="form-control" type="text" placeholder="Url youtube">
What I don't know is how to customize a custom validation:
For example in real time I use:
$this->validateOnly($field, [
'email' => 'unique:App\User,email|required|email'
]);
And it works great but with Laravel rules. But to customize I know it's different but I can't find how to do it.
For example for the Youtube url, on Stackoverflow I found the following solution:
Consisting of the following function:
$rx = '~
^(?:https?://)? # Optional protocol
(?:www[.])? # Optional sub-domain
(?:youtube[.]com/watch[?]v=|youtu[.]be/) # Mandatory domain name (w/ query string in .com)
([^&]{11}) # Video id of 11 characters as capture group 1
~x';
$has_match = preg_match($rx, $url, $matches);
Now how I can implement it with Livewire I don't know how to do it. What could I do?
EDITION:
I'm trying to do something like this: But the variable $rx gives me an error
$rx = '~
^(?:https?://)? # Optional protocol
(?:www[.])? # Optional sub-domain
(?:youtube[.]com/watch[?]v=|youtu[.]be/) # Mandatory domain name (w/ query string in .com)
([^&]{11}) # Video id of 11 characters as capture group 1
~x';
$this->validateOnly($field, [
'youtube_url' => "regex:$rx",
]);
ISSUE TWO:
I am testing with a Rules as follows:
public function passes($attribute, $value)
{
preg_match('/https:\/\/www\.youtube\.com\/watch\?v=[^&]+/', $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'La dirección de Youtube es inválida.';
}
And it seems that it never passes the validation, it always shows me the message I tried changing preg_match with various rules that I found on Google but it doesn't work.
When checking dd($value); the correct value always arrives.
I really appreciate one more help.
SOLUTION
Thanks @BetaM I had missed: return (bool)
return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$value);
We must keep in mind that one of the advantages of using Livewire is that we naturally have access to the benefits of Laravel .
Having said that, we can then proceed as follows:
Move logic from regular expression to custom validation rule
Once you
passes
have the logic in the method and in the method youmessage
describe the text when said regex is not fulfilled , you import your rule to your component in this way:Now in your validation you can do the following:
You can consider putting the validation in a method that is invoked in the click event associated with a
button
( that's up to you )