15

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?

shock_gone_wild
  • 6,262
  • 4
  • 25
  • 48
  • 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? – haakym Feb 12 '15 at 20:26
  • 2
    Besides writing a custom validator, a workaround might be to str_replace the umlauts before validating. str_replace(['ä','ö','ü'],['ae','oe','ue'],$request->url) – baao Feb 12 '15 at 20:30

2 Answers2

8

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!
}
Community
  • 1
  • 1
lukasgeiter
  • 124,981
  • 24
  • 288
  • 251
5

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",
shock_gone_wild
  • 6,262
  • 4
  • 25
  • 48