5

I'm trying to validate a double with two decimals but I can't achieve that. This is the regex and the errors I tryied and I got:

First try:

$validation = ['price' => 'regex:[0-9]+(\.[0-9][0-9]?)?'];

Error:

preg_match(): Unknown modifier '+'

Second try:

$validation = ['price' => 'regex:[0-9]+(\.[0-9][0-9]?)?'];

Error:

preg_match(): Delimiter must not be alphanumeric or backslash

Third try:

$validation = ['price' => 'regex:\d+(\.\d{2})?|\.\d{2}'];

Error:

preg_match(): Delimiter must not be alphanumeric or backslash

I got all the regex from this question: Simple regular expression for a decimal with a precision of 2

What am I doing wrong? Or there is any other way to validate a double with two decimals in Laravel?

Community
  • 1
  • 1
pableiros
  • 14,932
  • 12
  • 99
  • 105

3 Answers3

13

You need to use regex delimiters, the most common ones are /.../. Also, to make sure you match the entire string, you need anchors, ^ to anchor at the start and $ to anchor at the end:

$validation = ['price' => 'regex:/^[0-9]+(\.[0-9][0-9]?)?$/'];
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

try this code here below

'column' => 'required|regex:/^\d+(\.\d{1,2})?$/',
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
Abednego
  • 599
  • 10
  • 17
1

Just to improve Wiktor answer this part is used [0-9][0-9]? to check if we have one or two digits after decimal points where [0-9]? second one is optional. So this can be simplified by following

'regex:/^[0-9]+(\.[0-9]{1,2})?$/'

Here {1,2} tells how many digits we want after decimal point here at least one. So if someone wants more digits to be fixed e.g any want at most 3 digits after decimal point just change {1,2} to {1,3}.

Also to validate also negative numbers

'regex:/^(-)?[0-9]+(\.[0-9]{1,2})?$/'

Here adding (-)? checks optional minus numbers.

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58