1

I use the localization feature of laravel for the localization of my application. When I set the locale to german (de) (using App::setLocale()) and use the validator rule 'amount' => ['required', 'numeric', 'min:0'], I get an validation error when validating "100000,00". "100000.00" works.

The problem is, that the decimal separator should depend on the locale: "." (dot) for English, "," for German.

Furthermore, the "numeric" rule does not allow the thousands separator at all. It should be allowed. Whether dot or comma again depends on the locale.

Any idea how to solve this in a clean way?

jobo
  • 11
  • 2
  • You can implement a custom Validation Rule, and build a solution around this post (https://stackoverflow.com/questions/437371/php-locale-aware-number-format) I believe. – Kurt Friars Jul 08 '20 at 16:45
  • Thanx Kurt! That's what I thought, too. I was just wondering, whether this problem was already solved in an elegant way. Couldn't believe I was the only one localizing a website with laravel.:-) – jobo Jul 10 '20 at 13:06

1 Answers1

0

Based on the Laravel documentation I found the following solution:

In the boot() method of the AppServiceProvider.php extend the Validator like this:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
  /* validate international number format rule (depending on locale) */
  Validator::extend('intl_num', function ($attribute, $value, $parameters, $validator) {
      $numberFormatter = new \NumberFormatter(App::getLocale(), \NumberFormatter::DECIMAL);

      $num = $numberFormatter->parse($value);
      return ($num === false) ? false : true;
  });
  }
}

Now we can use the rule 'intl_num' for validation, e.g. in rules() method of a FormRequest class.

jobo
  • 11
  • 2