JavaScript RegEx Matches Invalid Number - javascript

I am getting inconsistent results when using JavaScript's RegEx to validate numbers with a decimal place. The goal is to have any combination of digits followed by a decimal point and two more digits. It works fine except with numbers in the thousands (no separators).
This is the expression I'm using:
^[0-9]+(\.[0-9][0-9])$
Valid numbers:
10.99
0.75
999.99
5000.99
...etc
Invalid Numbers:
1000
.75
0
...etc
The problem is that it matches whole numbers in the thousands. This is for an internal application so I'm not concerned about using additional separators. I've tested the expression out with tools like http://regexpal.com/ which gives me the results that I need, so it appears that there is something in the JS causing the issue.
You can duplicate the problem here:
http://jsfiddle.net/hcAcQ/

You need to escape the backslash before the ., I believe:
^[0-9]+(\\.[0-9][0-9])$
The reason that a 4 digit (or greater) number will work is because the single backslash isn't actually escaping that . to be a period character, thus causing it to act as the wildcard "match any character" dot.
When you have 3 or fewer digits this fails because there aren't enough characters for every match in the regex, but the with 4 digits it will work (one digit for the first character class, one for the ., and one each for the other two character classes.
Escaping the \ will cause the . to actually be interpreted as a literal . character, as you probably intended. You could also instead define your variable as a regex literal (MDN example; near the top) so that you don't have to deal with escaping \ characters within the string:
//instead of new valueFormat = new RegExp('^[0-9]+(\\.[0-9])$');
valueFormat = /^[0-9]+\.[0-9][0-9]$/;

This works(\. instead of .):
// valueFormat = new RegExp('^([0-9]+)(\.[0-9][0-9])$');
valueFormat = new RegExp('^([0-9]+)(\\.[0-9][0-9])$');

Related

Javascript regex to make sure that string matches format x:y

I am trying to parse a string which has two numbers, both can be between 1 and 3 digits, and will have a colon in between. Here are some examples:
"1:1"
"1:12"
"12:1"
"123:12"
Also, the given string may also be invalid, and I need to detect if it is. My attempts so far to make sure the string is valid have looked like this: .match(/[1-9]\:[1-9]/);. But then I noticed that this wont work if a string such as this is inputted: "characters12:4characters". How would I go about validating the string to make sure it is in the format x:y?
Any help would be deeply appreciated.
Edit: numbers which contain 0 at the beginning is valid, but may not be given.
You may use
/^\d{1,3}:\d{1,3}$/
See the regex demo
Details
^ - start of a string
\d{1,3} - one, two or three digits (\d is a shorthand character class that matches any digit (it can also be written as a [0-9] character class) and {1,3} is a limited quantifier that matches1 to 3 consecutive occurrences of the quantified subpattern)
: - a colon
\d{1,3} - one, two or three digits
$ - end of the string.

regex allows one character (it should not) why?

Hello I am trying to create a regex that recognizes money and numbers being inputted. I have to allow numbers because I am expecting non-formatted numbers to be inputted programmatically and then I will format them myself. For some reason my regex is allowing a one letter character as a possible input.
[\$]?[0-9,]*\.[0-9][0-9]
I understand that my regex accepts the case where multiple commas are added and also needs two digit after the decimal point. I have had an idea of how to fix that already. I have narrowed it down to possibly the *\. as the problem
EDIT
I found the regex expression that worked [\$]?([0-9,])*[\.][0-9]{2} but I still don't know how or why it was failing in the first place
I am using the .formatCurrency() to format the input into a money format. It can be found here but it still allows me to use alpha characters so i have to further masked it using the $(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" }); where input mask is found here and $(this) is a reference to a input element of type text. My code would look something like this
<input type="text" id="123" data-Money="true">
//in the script
.find("input").each(function () {
if ($(this).attr("data-Money") == "true") {
$(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" });
$(this).on("blur", function () {
$(this).formatCurrency();
});
I hope this helps. I try creating a JSfiddle but Idk how to add external libraries/plugin/extension
The "regular expression" you're using in your example script isn't a RegExp:
$(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" });
Rather, it's a String which contains a pattern which at some point is being converted into a true RegExp by your library using something along the lines of
var RE=!(value instanceof RegExp) ? new RegExp(value) : value;
Within Strings a backslash \ is used to represent special characters, like \n to represent a new-line. Adding a backslash to the beginning of a period, i.e. \., does nothing as there is no need to "escape" the period.
Thus, the RegExp being created from your String isn't seeing the backslash at all.
Instead of providing a String as your regular expression, use JavaScript's literal regular expression delimiters.
So rather than:
$(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" });
use
$(this).inputmask('Regex', { regex: /[\$]?([0-9,])*[\.][0-9]{2}/ });
And I believe your "regular expression" will perform as you expect.
(Note the use of forward slashes / to delimit your pattern, which JavaScript will use to provide a true RegExp.)
Firstly, you can replace '[0-9]' with '\d'. So we can rewrite your first regex a little more cleanly as
\$?[\d,]*\.\d\d
Breaking this down:
\$? - A literal dollar sign, zero or one
[\d,]* - Either a digit or a comma, zero or more
\. - A literal dot, required
\d - A digit, required
\d - A digit, required
From this, we can see that the minimum legal string is \.\d\d, three characters long. The regex you gave will never validate against any one character string.
Looking at your second regex,
[\$]? - A literal dollar sign, zero or one
([0-9,])* - Either a digit or a comma, subexpression for later use, zero or more
[\.] - A literal dot, required
[0-9]{2} - A digit, twice required
This has the exact same minimum matchable string as above - \.\d\d.
edit: As mentioned, depending on the language you may need to escape forward slashes to ensure they aren't misinterpretted by the language when processing the string.
Also, as an aside, the below regex is probably closer to what you need.
[A-Z]{3} ?(\d{0,3}(?:([,. ])\d{3}(?:\2\d{3})*)?)(?!\2)[,.](\d\d)\b
Explanation:
[A-Z]{3} - Three letters; for an ISO currency code
? - A space, zero or more; for readability
( - Capture block; to catch the integer currency amount
\d{0,3} - A digit, between one and three; for the first digit block
(?: - Non capturing block (NC)
([,. ]) - A comma, dot or space; as a thousands delimiter
\d{3} - A digit, three; the first possible whole thousands
(?: - Non capturing block (NC)
\2 - Match 2; the captured thousands delimiter above
\d{3} - A digits, three
)* - The above group, zero or more, i.e. as many thousands as we want
)? - The above (NC) group, zero or one, ie. all whole thousands
) - The above group, i.e everything before the decimal
[.,] - A comma or dot, as a decimal delimiter
(\d{2}) - Capture, A digit, two; ie. the decimal portion
\b - A word boundry; to ensure that we don't catch another
digit in the wrong place.
The negative lookahead was provided by an answer from John Kugelman in this question.
This correctly matches (matches enclosed in square brackets):
[AUD 1.00]
[USD 1,300,000.00]
[YEN 200 000.00]
I need [USD 1,000,000.00], all in non-sequential bills.
But not:
GBP 1.000
YEN 200,000

Regex which accepts alphanumerics only, except for one hyphen in the middle

I am trying to construct a regular expression which accepts alphanumerics only ([a-zA-Z0-9]), except for a single hyphen (-) in the middle of the string, with a minimum of 9 characters and a maximum of 20 characters.
I have verified the following expression, which accepts a hyphen in the middle.
/^[a-zA-Z0-9]+\-?[a-zA-Z0-9]+$/
How can I set the minimum 9 and maximum 20 characters for the above regex? I have already used quantifiers + and ? in the above expression.
How would I apply {9,20} to the above expression? Are there any other suggestions for the expression?
/^[a-zA-Z0-9]+\-?[a-zA-Z0-9]+$/
can be simplified to
/^[a-z0-9]+(?:-[a-z0-9]+)?$/i
since if there is no dash then you don't need to look for more letters after it, and you can use the i flag to match case-insensitively and avoid having to reiterate both lower-case and upper-case letters.
Then split your problem into two cases:
9-20 alpha numerics
10-21 characters, all of which are alpha numerics except one dash
You can check the second using a positive lookahead like
/^(?=.{10,21}$)/i
to check the number of characters without consuming them.
Combining these together gives you
/^(?:[a-z0-9]{9,20}|(?=.{10,21}$)[a-z0-9]+-[a-z0-9]+)$/i
You can do this provided you don't want - to be present exactly in middle
/^(?=[^-]+-?[^-]+$)[a-zA-Z\d-]{9,20}$/
[^-] matches any character that is not -

Regular Expression with optional elements in input string in javascript

Can anyone give me the regular expression for currency which have the following formats :
1000 - valid
1,000 - valid
1,000.00 or 1000.00 - valid.
This means, the number May or May Not contain a comma(,) separator every 3 digits.
The number May Or May Not contain a dot (.), and if it carries a dot(.) it should show atleast 1 number after the decimal place.
And lastly it should be numerical characters only. If I need to make my question clear kindly suggest.
/^\d{1,3}(?:(?:,\d{3})*|(?:\d{3})*)(?:\.\d{1,2})?$/
"Between one and three digits, then any number of groups of three digits prefixed by a comma or any number of groups of three digits not prefixed by said comma (disallowing a mix of the two kinds of groups), then an optional group of one or two digits prefixed by a dot."
Note: This regex assumes that you want to validate an entire string against the criteria outlined in your question. If you want to use it to find such numbers in a longer string, you will need to remove the ^ and $ from the beginning and end of the expression.
Something like so should work: (,?\d{3})+(\.\d{2})?. The regex will attempt to match a sequence of 3 digits precedeed by an optional comma, which is then, finally followed by an optional decimal point and 2 digits.
Please refer to this tutorial for more information.
EDIT: As per the comment below, the above regex can fail. I would recommend first using this regular expression: ^[\d][\d.,]+$ to make sure that you only have digits, thousand and decimal seperators. This regular expression will also make sure that the number starts with a digit, not with anything else. You could most likely have one regular expression which does everything, but it will most likely be quite complex.

JavaScript RegExp to match a (partial) hour

I want to allow people to enter times into a textbox in various formats. One of the formats would be either:
2h for 2 hours, or
2.5h for 2 and a half hours
I want to use a regex to recognise the pattern but it's not picking it up for some reason:
I have:
var hourRegex = /^\d{1,2}[\.\d+]?[h|H]$/;
which works for 2h, but not for 2.5h.
I thought that this regex would mean - Start at the beginning of the string, have one or two digits, then have none or one decimal points which if present must be followed by one or more digits then have a h or a H and then it must be the end of the string.
I have tried the regex tool here but no luck.
/^\d{1,2}(?:\.\d+)?h$/i; Use parentheses instead of square braces.
Start at the beginning
One or two digits
Optional: a dot followed by at least one digit
End with a h
Case insensitive
RegExp tuturial
[...] - square braces mean: anything which is within the provided range.
[^...] means: Match a character which is not within the provided range
(...) - parentheses mean: Group me. Optionally, the first characters of a group can start with:
?: - Don't reference me (me, I = group)
?= - Don't include me in the match, though I have to be here
?! - I may not show up at this point
{a,b}, {a,} means: At least a, maximum b characters. Omitting b = Infinity
+ means: at least one time, match as much as possible equivalen to {1,}
* means: match as much as possible equivalent to {0,}
+? and *? have the same effect as previously described, with one difference: Match as less as possible
Examples
[a-z] One character, any character between a, b, c, ..., z
(a-z) Match "a-z", and group it
[^0-9] Match any non-number character
See also
MDN: Regular Expressions - A more detailed guide
The trouble is here :
[\.\d+]
you can not use character classes inside brackets.
Use this instead:
(\.[0-9]+)?
You've confused your square brackets with your parenthesis. Square brackets look for a single match of any contained character, whereas parenthesis look for a match of the entire enclosed pattern.
Your issue lies in [\.\d+]? It's looking for . or 0-9 or +.
Instead you should try:
/^\d{1,2}(\.\d+)?(h|H)$/
Although that will still allow users to enter invalid numbers, such as 99.3 which is probably not the expected behavior.

Categories

Resources