laravel url validation umlauts
Asked Answered
N

2

20

I want to validate urls in laravel. My rules contain

"url" => "required|url"

This is working great. But when a user submits an url with umlauts, the rule check will always fail.

Chars like öäü etc.. are valid in German Domains. Is there a way in Laravel to accept these chars in urls?

Nectarine answered 12/2, 2015 at 20:24 Comment(2)
The only thing I can think of is to write a custom rule using regex, or you could check out how the url rule works in the framework and implement your own version of it, extending it?Gelman
Besides writing a custom validator, a workaround might be to str_replace the umlauts before validating. str_replace(['ä','ö','ü'],['ae','oe','ue'],$request->url)Bantu
A
9

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

"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:

$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!
}
Allysonalma answered 12/2, 2015 at 20:34 Comment(0)
N
6

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.

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

    "german_url"            => ":attribute is not a valid URL",
Nectarine answered 12/2, 2015 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.