-1

I am trying to validate a price field in Javascript.

The value can only be numbers, must have 1 decimal point, and must have 2 decimal places after it. Only 7 digits can be in front of the decimal point. Like: 1000000.00

Accepted:
123.00
1.01
0.01
4576.23
1234567.00
1.00

Not accepted:
0.00 (Cannot be free)
0.1 (not 2 decimal places)
1.0 (not 2 decimal places)
01.01 (Cannot start with 0)
12345678.00 (too many digits)
123 (no decimal point and 2 places)
-123.12 (negative, and unacceptable character)
123.123 (too many places)

I am unsure how to approach this problem and any help would be appreciated. A simple guide on how to do write my own regex would be helpful too as English is not my strong point. Thanks in advance.

Here's what I tried on my own: /^[0-9]+.[0-9]{2}$/ But I am unsure how to approach the 0 and length problem.

TryingToLearn
  • 33
  • 1
  • 6
  • 1
    First, check [How to ask](http://stackoverflow.com/help/how-to-ask). How to learn regex: do all lessons at [regexone.com](http://regexone.com/), read through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). Start answering regex-related questions here and you will learn on your own mistakes. – Wiktor Stribiżew Feb 01 '16 at 12:10

3 Answers3

1

This regular expression will solve your problem. I have checked it against all the options you have given in question.

^(0(?!\.00)|[1-9]\d{0,6})\.\d{2}$

If you don't know how to test a regular expression against a string in JavaScript you can check below link.

http://www.w3schools.com/jsref/jsref_regexp_test.asp

Puneet Singh
  • 3,141
  • 1
  • 20
  • 36
0

Try this pattern ^(?!^0\.00$)(([1-9][\d]{0,6})|([0]))\.[\d]{2}$

It excludes 0.00 and negative numbers and any spaces before or after the number (negative cases)

Hope I covered all possibilities

You can check for test cases here

Abdul Hameed
  • 845
  • 8
  • 24
0

The following regex pattern matches lines with 1 up to 7 digits followed by a "." and 2 more digits excluding those starting with 0 (or a letter)

^[1-9]\d{0,6}\.\d{2}$
Antoine
  • 76
  • 5