regular expression for valid 2 digit decimal number

后端 未结 2 1335
终归单人心
终归单人心 2021-01-05 10:05

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.

S

相关标签:
2条回答
  • 2021-01-05 10:19

    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.

    0 讨论(0)
  • 2021-01-05 10:25

    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

    0 讨论(0)
提交回复
热议问题