laravel url 验证变音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28487089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel url validation umlauts
提问by shock_gone_wild
I want to validate urls in laravel. My rules contain
我想验证 Laravel 中的网址。我的规则包含
"url" => "required|url"
This is working great. But when a user submits an url with umlauts, the rule check will always fail.
这很好用。但是当用户提交带有变音符号的 url 时,规则检查将始终失败。
Chars like ??ü etc.. are valid in German Domains. Is there a way in Laravel to accept these chars in urls?
??ü 等字符在德国域中有效。Laravel 有没有办法在 url 中接受这些字符?
采纳答案by lukasgeiter
Laravel uses filter_var()
with the FILTER_VALIADTE_URL
option which doesn't allow umlauts. You can write a custom validator or use the regex
validation rule in combination with a regular expression. I'm sure you'll find one here
Laravel 使用不允许变音filter_var()
的FILTER_VALIADTE_URL
选项。您可以编写自定义验证器或将regex
验证规则与正则表达式结合使用。我相信你会在这里找到一个
"url" => "required|regex:".$regex
Or better specify the rules as array to avoid problems with special characters:
或者更好地将规则指定为数组以避免特殊字符出现问题:
"url" => array("required", "regex:".$regex)
Or, as @michael points out, simply replace the umlauts before validating. Just make sure you save the real one afterwards:
或者,正如@michael 指出的那样,只需在验证之前替换变音即可。只需确保之后保存真实的:
$input = Input::all();
$validationInput = $input;
$validationInput['url'] = str_replace(['?','?','ü'], ['ae','oe','ue'], $validationInput['url']);
$validator = Validator::make(
$validationInput,
$rules
);
if($validator->passes()){
Model::create($input); // don't use the manipulated $validationInput!
}
回答by shock_gone_wild
Thanks @michael and @lukasgeiter for pointing me to the right way. I have decided to post my solution, in case someone has the same issue.
感谢 @michael 和 @lukasgeiter 为我指出正确的方法。我决定发布我的解决方案,以防有人遇到同样的问题。
I have created a custom Validator like:
我创建了一个自定义验证器,如:
Validator::extend('german_url', function($attribute, $value, $parameters) {
$url = str_replace(["?","?","ü"], ["ae", "oe", "ue"], $value);
return filter_var($url, FILTER_VALIDATE_URL);
});
My rules contain now:
我的规则现在包含:
"url" => "required|german_url,
Also don't forget to add the rule to your validation.php file
也不要忘记将规则添加到您的 validation.php 文件中
"german_url" => ":attribute is not a valid URL",