本文介绍在 laravel 8 控制器中对 youtube 嵌入链接(如 `https://www.youtube.com/embed/xxxxxxxx`)进行精准验证的两种专业方案:内联闭包验证与自定义验证规则类,兼顾灵活性与可维护性。
在 Laravel 8 中,仅靠内置的 url 规则无法确保输入是有效的 YouTube 嵌入地址(例如 https://www.youtube.com/embed/dQw4w9WgXcQ),因为它会接受任意合法 URL(如 https://google.com)。因此,需结合正则表达式进行语义级校验。以下是两种推荐实践:
直接在 validate() 方法中嵌入自定义逻辑,简洁高效:
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'subtitle' => 'required|string|unique:news,subtitle',
'category' => 'required|exists:categories,id
',
'link' => [
'required',
'url', // 先确保是格式正确的 URL
function ($attribute, $value, $fail) {
// 匹配 youtube.com 或 youtu.be 的嵌入/短链/标准播放页(支持 embed、watch?v=、youtu.be/ 等常见形式)
if (!preg_match('/^(https?:\/\/)?(www\.)?(youtube\.com\/embed\/|youtu\.be\/|youtube\.com\/watch\?v=|youtube\.com\/v\/)/i', $value)) {
$fail(__('validation.youtube_embed_url', [
'attribute' => __('general.url')
]));
}
}
],
'image1' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
'image2' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
'image3' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
'image4' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
'content' => 'required|string|min:10'
]);? 说明:该正则强调「必须包含 YouTube 嵌入路径特征」,如 /embed/、youtu.be/ 或 watch?v=,且忽略协议与大小写(i 修饰符),比原始答案中的宽松匹配更安全,避免误判 example.com?utm_source=youtube.com 类干扰项。
执行以下命令生成规则类:
php artisan make:rule YoutubeEmbedUrl
编辑 app/Rules/YoutubeEmbedUrl.php:
':attribute']);
}
}然后在控制器中使用:
use App\Rules\YoutubeEmbedUrl; // … 在 validate() 中: 'link' => ['required', 'url', new YoutubeEmbedUrl]
'youtube_embed_url' => ':attribute must be a valid YouTube embed or shareable URL (e.g., https://www.youtube.com/embed/xxxx or https://youtu.be/xxxx).'
通过以上任一方式,你即可在 Laravel 8 中实现精准、安全、可维护的 YouTube 嵌入 URL 校验,保障数据一致性与用户体验。