如何使用验证规则在Laravel中验证URL [英] How to validate url in laravel using validation rule
问题描述
我想使用php validate url函数来验证网站地址,但我不知道该如何实现.顺便说一句,我以这种方式尝试过,但没有用.
I want to validate a website address using php validate url function but i dont know how to achieve this. BTW i tried in this way but it doesnot work.
$url=filter_var($request->website, FILTER_VALIDATE_URL);
'website' => 'required|same:,'.$url
如果有人可以帮助我,那就太好了.
if someone can help me it would be great.
推荐答案
您可以使用Laravel的 url
验证器
You can use url
validator by Laravel
https://laravel.com/docs/5.8/validation#rule-url
'网站'=>'required | url'
或者,如果您想建立更精确的规则,则有几种方法可以执行.其中有一种,我认为最简单:
Or, if you want to build more precise rule, there is a few ways to do it. There is one of them, the simplest in my opinion:
在您的 AppServiceProvider @ boot
中:
Validator::extend('website', function ($attribute, $value, $parameters, $validator) {
// validation logic, e.g
return filter_var($value, FILTER_VALIDATE_URL);
});
然后在验证者列表中使用您的规则:
And then use you rule in validators list:
'website' => ['required', 'website'],
此处说明的所有内容: https://laravel.com/docs/5.8/validation#custom-validation-rules
Everything explained here: https://laravel.com/docs/5.8/validation#custom-validation-rules
这篇关于如何使用验证规则在Laravel中验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!