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

前端 未结 2 648
不思量自难忘°
不思量自难忘° 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:05

    Laravel supports regex pattern in validation rule so you can use the given pattern to match something like 12,365.00 and it's recommended to use an array instead of pipe when using regular expressions as a rule

    $rules = array('amount' => array('match:/^[0-9]{1,3}(,[0-9]{3})*\.[0-9]+$/'));
    

    Check this link. Also, if you want to remove the commas for any reason then check this answer.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题