I want to validate my youtube URL like this https://www.youtube.com/embed/xxxxxxxx. How to use the regex in variable link for this?
my code is like this in controller
$validatedData = $request->validate([
'title' => 'required',
'subtitle' => 'required|unique:news',
'category' => 'required',
'link' => 'required|regex:??',
'image1' => 'required|image',
'image2' => 'image',
'image3' => 'image',
'image4' => 'image',
'content' => 'required'
]);
CodePudding user response:
You need to add some custom validation logic for achieving this .Hope this code snippet can help you-
'link' => [
'required',
'url',
function ($attribute, $requesturl, $failed) {
if (!preg_match('/(youtube.com|youtu.be)\/(embed)?(\?v=)?(\S )?/', $requesturl)) {
$failed(trans("general.not_youtube_url", ["name" => trans("general.url")]));
}
},
]
Or like below-
public function passes($attribute, $requesturl)
{
return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$requesturl);
}
'link' => new RuleYoutube,