pableiros pableiros - 3 months ago 39
PHP Question

Laravel double validation regex not working

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
?

Answer

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]?)?$/'];
Comments