4

I am trying to build a regex expression with this requirement .

Requirement :

Max length - 5(inc decimal dot if is a decimal number)

Decimal precession - max 2 digits (if it is a decimal numer ).

Number - need not to be a decimal number (not mandatory)

Code:

<script>
function myFunction() {
   var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
    var num = 12345.52; // i will test here indiffernt ways
    var n = regexp.test(num)
    document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>

Output should look like :

12345.52 -->It should return false as length is 8 inc dot but it returns true

123456.52 --> false . I came to know d{0,5} is looking for before decimal

12.45 --> true . Perfect one (length 5 , precession 2 )

12345 --> true . Perfect one (length 5 , precession- not madatory)

I am hoping to build a regex expression satisfies all the above scenarios .

Reference : Click Here

Community
  • 1
  • 1
super cool
  • 6,003
  • 2
  • 30
  • 63

1 Answers1

6

You could try the below regex which uses positive lookahead assertion.

^(?=.{1,5}$)\d+(?:\.\d{1,2})?$

DEMO

Explanation:

  • ^ Asserts that we are at the start.
  • (?=.{1,5}$) Asserts that the length must be from 1 upto 5.
  • \d+ Allows one or more digits.
  • (?:\.\d{1,2})? Optional decimal part with the allowable digits after the decimal point must be one or two.
  • $ Asserts that we are at the end of the line.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • cant thank you more buddie. sadly there is small correction in my question requirement can i edit or should i post as a new one ? – super cool Oct 08 '14 at 16:29
  • 1
    ask me . If i don't know the answer then you go for edit(**no**) or another question. Say your new requirement. – Avinash Raj Oct 08 '14 at 16:31
  • forget about length now i just need regex for a number if it is integer it should be 3 digits max and if its decimal it should be of 3 digit max before dot and precession of 2 max like `123.45` – super cool Oct 08 '14 at 16:42