4

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
  • 12,936
  • 11
  • 88
  • 94

3 Answers3

12

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
  • 561,645
  • 34
  • 376
  • 476
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
  • 4,767
  • 3
  • 29
  • 51
1

try this code here below

'column' => 'required|regex:/^\d+(\.\d{1,2})?$/',
Maximilian Ast
  • 3,240
  • 12
  • 39
  • 46
Abednego
  • 501
  • 9
  • 16