Samuel De Backer Samuel De Backer - 1 year ago 409
PHP Question

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

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 rule is:

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

What’s the best method :

  • Keep the rule and replace comma with point before validation ? Is there a before_validation observer or something like this ?

  • Build a custom validation rule ? french_numeric for example ?

Answer Source

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.