Aishwarya
Aishwarya

Reputation: 11

Regular expression is not working properly in javascript

I am doing amount validation. The requirements are:

  1. There should not be a leading zero.
  2. It should accept only numbers.
  3. There should be a single decimal point.
  4. it should accept 9 digits before decimal and 2 digits after decimal.

I have tried this regex:

/^(([1-9]\d{0,8})(\.\d{1,2})?)/g;

The issue is, after entering 9 digits, decimal is getting entered only if you enter any digits along with it simultaneously (at a time), without it I am unable enter decimal point.

Upvotes: 1

Views: 75

Answers (1)

emartinelli
emartinelli

Reputation: 1047

This could help:

/^(?!0)\d{1,9}\.\d{0,2}$/

In this case, I used a lookahed ((!?0)) to prevent a leading zero, then used a similar OP expression to match the string. It means that everything in expression \d{1,9}\.\d{0,2} and not preceded by a zero will be matched.

Demo

Upvotes: 1

Related Questions