What's the best way to validate numbers with comma as decimal separator?

前端 未结 2 649
不思量自难忘°
不思量自难忘° 2021-01-18 22:45

In a Laravel app, I have a form on which I need to validate numbers with a comma as the decimal separator. For the moment, it only works with a point because my validation r

2条回答
  •  粉色の甜心
    2021-01-18 23:18

    Building on the excellent answer from The Alpha, here is a code snippet to make a float validation configurable.

    Add this snippet to the boot() function in your AppServiceProvider class (tested with Laravel 5.4):

    Validator::extend('float', function ($attribute, $value, $parameters, $validator) {
        $thousandsSeparator = env('APP_NUMBER_THOUSANDS_SEPARATOR') == '.' ? '\\' . env('APP_NUMBER_THOUSANDS_SEPARATOR') : env('APP_NUMBER_THOUSANDS_SEPARATOR');
        $commaSeparator = env('APP_NUMBER_COMMA_SEPARATOR') == '.' ? '\\' . env('APP_NUMBER_COMMA_SEPARATOR') : env('APP_NUMBER_COMMA_SEPARATOR');
        $regex = '~^[0-9]{1,3}(' . $thousandsSeparator . '[0-9]{3})*' . $commaSeparator . '[0-9]+$~';
        $validate = preg_match($regex, $value);
    
        if ($validate === 1) {
            return true;
        }
    
        return false;
    });
    

    Your .env-file would have those two lines:

    APP_NUMBER_COMMA_SEPARATOR="."
    APP_NUMBER_THOUSANDS_SEPARATOR=","
    

    And your rule would look like this:

    $rules = [
        'amount' => 'float|min:0',
    ];
    

    Note: I'm only escaping the . correctly. If you are going to use charaters that have special meaning in regex syntax (like * or +) you have to escape them too.

    But since a float number like 550*345,00 (550,345.00) or 57+44 (57.44) wouldn't make sense I've ignored this issue.

    Kind regards

提交回复
热议问题