Kalpesh Koli
Kalpesh Koli

Reputation: 123

Do not allow decimal points after 10 digits using regex

I want to allow only digits in a text box using regex expression.

Valid expressions:

999999999.22
1234567890
123447899.1

Invalid expressions:

99999999999
9999999999.12
9999999999.1
99999999999.12
99999999999.1

I have tried below regular expression which does all I want expect one thing: It allows decimal points after 10 digits, which I do not want. Decimal points should only be valid after a maximum of 9 digits.

^[0-9]\\d{0,9}(\\.\\d{1,2})?%?$

Upvotes: 2

Views: 506

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

You could match either 1 - 9 digits followed by 1 or 2 decimals or 1 - 10 digits using an alternation:

^(?:\d{1,9}\.\d{1,2}|\d{1,10})$

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157136

You can split your regex in three parts: 1 to 10 digits, 1 to 9 digits and 1 decimal and 1 to 8 digits and 2 decimals:

^\d{1,10}$|^\d{1,8}\.\d{2}$|^\d{1,9}\.\d$

(Proof)

Upvotes: 2

Related Questions