我想使用php validate url函数来验证网站地址,但我不知道该如何实现。顺便说一句,我以这种方式尝试过,但没有用。
$url=filter_var($request->website, FILTER_VALIDATE_URL);
'website' => 'required|same:,'.$url
如果有人可以帮助我,那就太好了。
答案 0 :(得分:1)
您可以使用Laravel的url
验证器
https://laravel.com/docs/5.8/validation#rule-url
'website' => 'required|url'
或者,如果您想建立更精确的规则,则有几种方法可以执行。 其中有一种,我认为最简单:
在您的AppServiceProvider@boot
中:
Validator::extend('website', function ($attribute, $value, $parameters, $validator) {
// validation logic, e.g
return filter_var($value, FILTER_VALIDATE_URL);
});
然后在验证者列表中使用您的规则:
'website' => ['required', 'website'],
一切都在这里解释:https://laravel.com/docs/5.8/validation#custom-validation-rules
答案 1 :(得分:0)
Laravel将filter_var()
与FILTER_VALIADTE_URL
选项结合使用,该选项不允许变音。您可以编写自定义验证程序,也可以将正则表达式验证规则与正则表达式结合使用。
$regex ="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/";
// specify the rules as array to avoid problems with special characters:
"website" => array("required", "regex:".$regex)
答案 2 :(得分:0)
我知道我回答的有点晚了,但昨晚我遇到同样的问题时学会了创建正则表达式,事实上,这是我创建的第一个正则表达式。到目前为止,我能够解决我的问题。
PHP:8.0.3
Laravel: 7.x
app/Rules/DomainNameRule.php
class DomainNameRule implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(
private $caption = 'Website'
) {
$this->caption = $caption;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match("/^((https?:\/\/)?([w]{3}[\.])?)?[a-zA-Z0-9\-_]{2,}[\.][a-zA-Z]{2,4}([\.][a-zA-Z]{2,6})?$/", $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return @implode('<br>', [
"{$this->caption} - Invalid",
"- Can start with 'http://www' or 'https://www'",
"- Must has a domain name (google | microsoft | yahoo | .etc)",
"- Must end with domain type (.com | .co.in | .online | .etc)",
"- Special characters allowed: _-",
"e.g. https://www.google.com | https://www.google.co.in"
]);
}
}
use App\Rules\DomainNameRule;
...
'website' => ['required', new DomainNameRule];
这是 youtube 视频的链接,它在我学习创建正则表达式时非常有用:https://youtu.be/zAAXtLo0zuw