What is the best way to test comma numbers as decimal separator?

In a Laravel application, I have a form on which I need to check semicolons as a decimal separator. At the moment, it only works with a dot, because my validation rule is:

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

Which is the best method:

  • Save the rule and replace the comma with a period before checking? Is there a before_validation observer or something like this?
  • Create your own validation rule? For example, french_numeric?
+4
source share
2 answers

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

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

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

+9
source

Based on an excellent answer from Alpha, here is a code snippet to do a float validation.

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 will have two lines:

 APP_NUMBER_COMMA_SEPARATOR="." APP_NUMBER_THOUSANDS_SEPARATOR="," 

And your rule will look like this:

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

Note. I'm just running away . right. If you intend to use charaters that have special meaning in regex syntax (e.g. * or +), you should also avoid them.

But since a floating point number , for example 550*345,00 (550,345.00) or 57+44 (57.44) , does not make sense, I ignored this problem.

Yours faithfully

+1
source

Source: https://habr.com/ru/post/1491248/


All Articles