6

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?

4
  • 2
    Try $validation = ['price' => 'regex:/[0-9]+(\.[0-9][0-9]?)?/']; Commented Aug 14, 2016 at 22:24
  • 1
    @WiktorStribiżew Thank you it works, but is it any way to prevent more than two decimals? Commented Aug 14, 2016 at 22:29
  • 2
    You mean to only allow, say, 1.22 and not 1.233? Try $validation = ['price' => 'regex:/^[0-9]+(\.[0-9][0-9]?)?$/']; Commented Aug 14, 2016 at 22:30
  • 1
    @WiktorStribiżew yes, thank you very much !! Commented Aug 14, 2016 at 22:31

3 Answers 3

14

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]?)?$/'];
Sign up to request clarification or add additional context in comments.

Comments

3

try this code here below

'column' => 'required|regex:/^\d+(\.\d{1,2})?$/',

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.