Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal or numeric values in regular expression validation

I am trying to use a regular expression validation to check for only decimal values or numeric values. But user enters numeric value, it don't be first digit "0"

How do I do that?

like image 302
ilkdrl Avatar asked May 11 '10 13:05

ilkdrl


People also ask

What is the regex for decimal number?

A better regex would be /^\d*\.?\ d+$/ which would force a digit after a decimal point. @Chandranshu and it matches an empty string, which your change would also solve.

How do you validate decimals?

To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.

How do you validate a regular expression?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.

Can you use regex with numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


1 Answers

A digit in the range 1-9 followed by zero or more other digits:

^[1-9]\d*$ 

To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:

^[1-9]\d*(\.\d+)?$ 

Notes:

  • The ^ and $ anchor to the start and end basically saying that the whole string must match the pattern

  • ()? matches 0 or 1 of the whole thing between the brackets

Update to handle commas:

In regular expressions . has a special meaning - match any single character. To match literally a . in a string you need to escape the . using \. This is the meaning of the \. in the regexp above. So if you want to use comma instead the pattern is simply:

^[1-9]\d*(,\d+)?$ 

Further update to handle commas and full stops

If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:

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

i.e. this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.

If you want to allow a . anywhere between the digits then try:

^[1-9][\.\d]*(,\d+)?$ 

i.e. a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.

like image 57
mikej Avatar answered Sep 19 '22 03:09

mikej