8

I want to have a validation in php for price which can be 100 or 100.45 The 2 decimal places will be optional.

Now the validation should allow only digits.

So far i managed to achieve it

if (!preg_match('/^[0-9]+(\.[0-9]{1,2})?/', "100")) { echo "Invalid"; } else { echo "Valid"; } 

but the issue here is that it is showing valid even if i enter 100a.00 or 100a or 100.a00

Please help me in fixing it so that only digits are allowed i.e 100 or 100.00 format

1
  • 1
    Have you tried adding a $ at the end, to match the end of the string? At the moment, it's matching a valid sequence of characters at the start with ^, so 100a is valid - the a is ignored, because the 100 is valid. Commented May 16, 2013 at 13:00

2 Answers 2

21

Try this:

if (!preg_match('/^[0-9]+(\.[0-9]{1,2})?$/', "100")) 

The $ denotes the "end of a string": http://www.php.net/manual/en/regexp.reference.meta.php

Sign up to request clarification or add additional context in comments.

1 Comment

what if the number length is more than 2.
7

Lacks a $ in your regex. Presently, the first 3 characters in '100a...' match your regex.

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

should do the trick.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.