Surya sasidhar
Surya sasidhar

Reputation: 30313

Number validation using a regular expression

In a web application, while validating the textbox using a regular expression, I have written the expression to validate only digits not starting with zero, with 3 digits after the decimal points. But if I type only a single digit, it's giving me a message. Can you help me with the regular expression? I'm looking for an expression which would not accept a leading digit of zero and accept only 3 decimals like 12.336, 1.254, 10.20, etc.

Upvotes: 0

Views: 4212

Answers (3)

josko
josko

Reputation: 33

This should do the trick:

[1-9]\d*\.?\d{0,3}

If you wish to ignore whitespace, just add \s*:

\s*[1-9]\d*\.?\d{0,3}\s*

BTW, there are ton of visual tools for writing regular expressions – I recommend Expresso.

Upvotes: 1

Toto
Toto

Reputation: 91415

Depending on exactly what you want:

This will match numbers not begining with 0 and having exactly 3 decimal

^[1-9]\d*\.\d{3}$

This will match numbers not begining with 0 and having 1 to 3 decimal or none.

^[1-9]\d*(?:\.\d{1,3})?$

Upvotes: 1

m.edmondson
m.edmondson

Reputation: 30882

This is what you want:

^[1-9]\d*.?\d{0,3}$

Note this will also fail if there are spaces at either end of the string, remove the ^ at the start and the $ at the end if this is not as desired.

Upvotes: 0

Related Questions