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 开发者_JS百科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.
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})?$
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.
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.
精彩评论