Regex for number with decimals and thousand separator - javascript

I need regex to validate a number that could contain thousand separators or decimals using javascript.
Max value being 9,999,999.99
Min value 0.01
Other valid values:
11,111
11.1
1,111.11
INVALID values:
1111
1111,11
,111
111,
I've searched all over with no joy.

/^\d{1,3}(,\d{3})*(\.\d+)?$/
About the minimum and maximum values... Well, I wouldn't do it with a regex, but you can add lookaheads at the beginning:
/^(?!0+\.00)(?=.{1,9}(\.|$))\d{1,3}(,\d{3})*(\.\d+)?$/
Note: this allows 0,999.00, so you may want to change it to:
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
which would not allow a leading 0.
Edit:
Tests: http://jsfiddle.net/pKsYq/2/

((\d){1,3})+([,][\d]{3})*([.](\d)*)?
It worked on a few, but I'm still learning regex as well.
The logic should be 1-3 digits 0-1 times, 1 comma followed by 3 digits any number of times, and a single . followed by any number of digits 0-1 times

First, I want to point out that if you own the form the data is coming from, the best way to restrict the input is to use the proper form elements (aka, number field)
<input type="number" name="size" min="0.01" max="9,999,999.99" step="0.01">
Whether "," can be entered will be based on the browser, but the browser will always give you the value as an actual number. (Remember that all form data must be validated/sanitized server side as well. Never trust the client)
Second, I'd like to expand on the other answers to a more robust (platform independent)/modifiable regex.
You should surround the regex with ^ and $ to make sure you are matching against the whole number, not just a subset of it. ex ^<my_regex>$
The right side of the decimal is optional, so we can put it in an optional group (<regex>)?
Matching a literal period and than any chain of numbers is simply \.\d+
If you want to insist the last number after the decimal isn't a 0, you can use [1-9] for "a non-zero number" so \.\d+[1-9]
For the left side of the decimal, the leading number will be non-zero, or the number is zero. So ([1-9]<rest-of-number-regex>|0)
The first group of numbers will be 1-3 digits so [1-9]\d{0,2}
After that, we have to add digits in 3s so (,\d{3})*
Remember ? means optional, so to make the , optional is just (,?\d{3})*
Putting it all together
^([1-9]\d{0,2}(,?\d{3})*|0)(\.\d+[1-9])?$

Tezra's formula fails for '1.' or '1.0'. For my purposes, I allow leading and trailing zeros, as well as a leading + or - sign, like so:
^[-+]?((\d{1,3}(,\d{3})*)|(\d*))(\.|\.\d*)?$

In a recent project we needed to alter this version in order to meet international requirements.
This is what we used: ^-?(\d{1,3}(?<tt>\.|\,| ))((\d{3}\k<tt>)*(\d{3}(?!\k<tt>)[\.|\,]))?\d*$
Creating a named group (?<tt>\.|\,| ) allowed us to use the negative look ahead (?!\k<tt>)[\.|\,]) later to ensure the thousands separator and the decimal point are in fact different.

I have used below regrex for following retrictions -
^(?!0|\.00)[0-9]+(,\d{3})*(.[0-9]{0,2})$
Not allow 0 and .00.
','(thousand seperator) after 3 digits.
'.' (decimal upto 2 decimal places).

Related

Why this regex fails when there is an extra zero?

I have created this regex to match dollar amounts more than $9,000.00.
\$(?=.{6,11}$)\d{1,3}(?:,\d{3})*
But it fails in cases like this,
$25,000.00. Text Goes here
$1,000,000.00
However it works in cases like this,
$25,000.0. T
$25,000.00
$999,000.00
How to fix this regex?
Some issues in your regex:
The look ahead assertion requires the that match can only start in the final 11 characters of the input string, since it has the $ anchor after at least 6 and at most 11 characters. So it is no surprise that "$25,000.00. Text Goes here" does not match. I suppose you don't want that $ anchor, and then the 11 is not useful anymore either.
The look ahead assertion requires that at least 6 characters follow after the currency symbol, however that could include non-digit characters, and so your regex will match the amount in `$300 oh" (6 characters follow after currency symbol).
There is no provision in your regex for decimals even though you say it works for examples that have decimals. But it will not include those decimals in the match. For instance, for input "$300,000.50" it will only match "$300,000" and not the 50 cents. You would need to accept an optional decimal point followed by one or two digits and then require there are no more decimal digits with a negative look-ahead.
The look-ahead assertion is not the right place to impose a maximum amount, because when you remove the $ (see first point) you must still require that there are no more digits after the 11th position. Instead, just remove the look-ahead assertion and match the patterns you want in more detail. There are just two options: either you have 2 or 3 digits followed by one digit group (for amounts between 10,000 and 999,999.99) or you have 1 to 3 digits followed by two digit groups (for amounts between 1,000,000 and 999,999,999.99). To avoid that more digits follow when no decimal part exists, use a negative look-ahead assertion: (?![,.]?\d).
All this is taken into account in this correction:
\$(?:\d{2,3}(?:,\d{3})|\d{1,3}(?:,\d{3}){2})((?![,.]?\d)|\.\d\d?(?!\d))
On regex101
To allow the same numbers without commas, add \d{5,9} as an option:
\$(?:\d{2,3}(?:,\d{3})|\d{1,3}(?:,\d{3}){2}|\d{5,9})(?:(?![,.]?\d)|\.\d\d?(?!\d))
On regex101
Totally new answer. After closer inspection I see that they have revised
the specifications on this question.
I am submitting this solution based on a $10,000.00 - $999,999,999.00 range
of unacceptable cash amounts. The comma's and decimal are optional.
There cannot be more than 3 consecutive decimal numbers after the period.
Ah, other specifications are dubious.
Note that a text representation of leading zero's is not allowed, which is a
distinction worth investigating as digits \d class is covers characters 0-9.
It is hard, if not impossible to match to infinity.
For example, the OP requested to match cash greater than $9,000 (Ah $10,000).
Regex has no representation of quantifiers representing infinity therefore
#Trincot tried to talk him into a max cash amount number to cap it.
In reality, you can only match the infinite with a negative of the finite.
So it is in the cosmos as it is in regex.
The only real way to match a number greater than another number is to
state that it is not in a finite range. In this case not in the range $0 - $9,999.
In this case they have established a range that the cash cannot be in.
That apparently is this $10,000.00 - $999,999,999.00 range, which
absolutely does not represent all values greater than $10,000.00
My original answer was to match $0 - $9,000 (original minimum) then post that regex in a negative assertion, thereby matching the infinite set of values
greater than $9,000 which was and is the only answer to matching cash values greater than
a fixed amount.
In the end, parsing values is only a preamble to getting it into a float
and there is no way to glean the final value ahead of that conversion.
Therefore, this is really an exercise in futility.
To that end :
$10,000.00 - $999,999,999.00
\$[1-9](?:\d{1,2}(?:,?\d{3}){1,2}|(?:,?\d{3}){2})(?:\.\d{0,2})?(?![,.]?\d)
https://regex101.com/r/1h4XW9/1
\$ [1-9]
(?:
\d{1,2}
(?: ,? \d{3} ){1,2}
| (?: ,? \d{3} ){2}
)
(?: \. \d{0,2} )?
(?! [,.]? \d )

Javascript Regex for amount field(not allow digits other then zero after decimal point)

I am doing amount validation and i want to write a regular expression in the below format,
1) It should not allow digits but zero(0) can allow after decimal point (i.e, not allow numbers like 23.33, 12.24 but allow 13.00)
2) Decimal point not mandatory for the amount field
I tried using the following code but its taking digits after decimal point,
/^(?!0)\d+(\.\d{1,2})?$/)
Forget about regex, all you need is check if :
function is_valid(num) {
return num == (num|0)
}
console.log(is_valid(24.33))
console.log(is_valid(23.00))
console.log(is_valid(12))
console.log(is_valid('12.67'))
console.log(is_valid('12.00'))
A better method for ECMA Script 2015 or later: Number.isInteger(num) (IE not supported) (I have to admit
that it may be slower, though.)
Besides num | 0 which floors a number, sometimes I will also use ~~num. There are many other methods like Math.floor(num), though. See here for more information.
But if you really like a regular expression (not suggested): /^\s*[+-]?\d+(\.0*)?\s*$/
Remove \s* to disallow spaces.
Change [+-] to - to disallow positive signs.
Change 0* to 0{0,2} or 0{1,2} to allow only up to 2 d.p.
Visit here to design and check your own regular expression.
Document for Number.isInteger
Actually you should use <input type="number"> instead. (IE 10+)

Height and weight Validation in javascript

I need a regular expression to allow a person to enter their height in the following format either
5'10 or 5'10" making the quotation marks optional for the inches. There also could be a space between the feet and inches like 5' 10 or 5' 10".
thanks for the help in advance.
You should be able to use /\d+'\s?\d+"?/ that will allow the numbers to be multiple digits long, requires the single quote after the first number, allows an optional space after the single quote and optionally selects the double quote.
The following will ensure that the number of feet is no greater than 9 and that the inches are between 0 and 11.
/^\d' ?(?:\d|1[0-1])"?$/
If you wanted to make sure the person is at least 2 feet tall, for example, you can just replace the initial \d with the appropriate range.
/^[2-9]' ?(?:\d|1[0-1])"?$/
For weight validation, you can do something like the following, which will ensure the user enters 2 or 3 digits followed by "kg", with an optional space in between. This can easily be adapted for "lbs", or the units can simply be omitted, depending on your requirements.
/^\d{2,3} ?kg$/
I think you might benefit from reading up on regular expressions and testing them out for yourself.

Regular Expression: Help Matching a number less than 24

so I'm making this regular expression to verify some text boxes on a website that I'm designing for an internship.
The problem is that I'm not so keen on regular expressions, and I'm close to having a working one that matches a number between 0-24 and no more than two decimal places.
This is what I have so far. The pattern is also matching any string; such as, "a" or "az".
var pattern = "^([0-9]{0,2}?.?[0-9]{0,2}|1[0-9].?[0-9]{0,2}|2[0-4].?[0-9]{0,2})$";
To get a number between 0 and 24 (24 excluded) with optional up to two decimal places:
^(\d|1\d|2[0-3])(\.\d{1,2})?$
The decimal part:
\. - match the decimal dot
\d{1,2} - one or two digits
()? - makes it optional
The whole part:
\d - numbers 0-9
1\d - numbers 10-19
2[0-3] - numbers 20-23
(x|y|z) - one of x, y or z
As for the "why is my version matching things like "a" and "az" part" - it's a little complex, but it basically boils down to you using dots (like .?). In regex, a dot means "any one character". To make it match a literal dot, you need to escape it with a slash just like I did.
Minor remark: If you want optional leading zero for single digit numbers, replace 1\d with [01]\d. If you want mandatory leading zero for single digit numbers, replace \d|1\d with [01]\d. If you don't want leading zeroes, leave it as it is.
Assuming you do not want 05 or 5.50
^((?:[0-9]|1[0-9]|2[0-3])(?:\.(?:[1-9]|[0-9][1-9]))?)$
You can try it here
The following is a quick attempt to match a floating point number from 0 to 24.99 with up to two non-zero digits
^(([0-9])|([01][0-9])|(2[0-4]))(\.[0-9]{1,2})?$
I think it might be easier to use math to do this though...
You can see the explanation of the entire regex as well as test it out here. I have also added a few test cases.
^(\d|[01]\d|2[0-3])(\.\d{1,2})?$
Test cases:
Valid:
22
1.29
2.99
9.99
13.24
17.38
20.01
02.15
15.35
23.56
1.1
Invalid:
24.29
235.215
21.256
To get a integer number between 1 and 23: ^([1-9]|1[0-9]|2[0-3])$

Reg Expression Javascript for Millions with limit

I am looking to create a regular expression in javascript that does the following:
Allows for 1 or more numbers
Then has an optional period (".")
Then has an optional number of digits up to 6
The context is that i need people to enter in numeric values in the millions and i want them to at least include a 0 if they are entering thousands... so they could enter the following:
1 (would be one million)
0.725 (would be 725k)
10.5 (would be 10M 500K)
I also need to ensure that the value doesn't reach over 725.00 (or 725 million).
Thanks in advance.
That sounds like:
/^(?!\d{4})(?![89]\d\d)(?!7[3-9]\d)(?!72[6-9])(?!725\.0*[1-9])(0|[1-9]\d*)(\.\d{1,6})$/
which means:
doesn't start with four digits (i.e., is less than 1000)
doesn't start with 8 or 9 followed by two digits (i.e., is less than 800)
doesn't start with 73-79 followed by a digit (i.e., is less than 730)
doesn't start with 726-729 (i.e., is less than 726)
doesn't start with 725. followed by zero or more zeroes followed by a nonzero digit (i.e., is less than or equal to 725.00).
starts either with 0, or with 1-9 followed by zero or more digits
after that, optionally a decimal point followed by between one and six digits
That said, I'd actually recommend implementing the above as several separate checks, rather than cramming it all into one regex like the above. In particular, the "is less than or equal to 725.00" check is probably better implemented using numeric comparison; and even if you do want to use a regex for that, you probably want to detect it as a separate error from 0.1asefawe so you can give a more precise error-message.
So basically you want a number that would be multiplied by 10^6 to get the true value.
This sounds like a two-stepper; First, verify that the input string is in a format you expect (you can use a regex for this very easily). Then, parse the string into a number variable and test the actual value. The regex pattern for that would look like "[0-9]{1,3}(\.[0-9]{1,6})?", basically matching a number with up to 3 whole digits and 6 fractional digits, the decimal place and fractional digits being optional. If it matches this pattern, then it's parsable into a number, and you can then perform a quick check that your number <= 725.
I honestly don't think it's feasible to create a single Regex that can validate a proper numeric format AND an inclusive maximum range, but here's a start:
"^(725(\.0{1,6})|(([7][2][0-4]|[7][0-1][0-9]|[1-6][0-9]{2}|[1-9][0-9]|[0-9])(\.[0-9]{1,6})?)$"
This will allow any natural whole number from zero to 724, with any fractional part up to six digits from ".000001" to ".999999". It does this in stages; it will match 720-724, or 700-719, or any three-digit number up to 699, or any two-digit number, or any one-digit number. Then, it will also match the quantity "725" explicitly, with an optional decimal point and up to 6 zeroes.
EDIT: While your comment states that you used this pattern, and it does produce the correct result, I had intended it as a "what not to do"; this pattern will be far more costly to evaluate than the first solution, just to avoid a server-side rule check. And you will have to perform a server-side validation anyway; anything done within the confines of the user's browser should be suspect because the user can disable JavaScript or can even use browser plug-ins like FireBug to make your HTML page behave the way he wants, instead of the way you designed it.

Categories