Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel double validation regex not working

Tags:

regex

php

laravel

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?

like image 751
pableiros Avatar asked Dec 07 '22 21:12

pableiros


1 Answers

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]?)?$/'];
like image 97
Wiktor Stribiżew Avatar answered Dec 26 '22 10:12

Wiktor Stribiżew