Reg Expression Javascript for Millions with limit - javascript

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.

Related

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+)

A limit with one or two numeric digits Regex

I am trying to figure out how to create a regex that will let me search for not only one or double digits, but also have a limit from 1-60. I want double digits to be applicable as well so for example, 01-09 works just as well as 1-9.
^([1,2,3,4,5]\d{0,1}|(60))
is what I have so far in terms of setting up the the double digits, but I then can't get 7, 8, 9 to pass as either single or double digits. Any idea on how to solve this problem or do I need to do a case by case approach?
try this;
^0*([1-9]$|^[1-5][0-9]$|^60$)
from this generator
ie, can either be just 1-9, or 1-5 followed by 1-9, or 60 itself.
Edit amended to force begining and end of string and allows leading zeros

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.

How to write a regular expression to validate a 4 character string as a non-zero binary number?

I have a string E.g 1001, which needs to be exactly 4 chars and can be any combination of 0 and 1, but not all zeros (all ones is ok).
I thought of:
^[01]{4}$
won't work because it accepts 0000
I will be using PHP or JavaScript to do this.
Just adding a detail.
I will be using this to validate the answers for a multi choise questionnaire before they go in the database therefore the string will have length N depending on the number of choices for the question.
so a function to provide the general solution would be great.
It should work
^(?!0000)[01]{4}$
DEMO
Note: Use gm as modifier
Read more about Lookahead and Lookbehind Zero-Length Assertions that actually matches characters, but then gives up the match, returning only the result: match or no match.
Pattern explanation:
^ the beginning of the string
(?! look ahead to see if there is not:
0000 '0000'
) end of look-ahead
[01]{4} any character of: '0', '1' (4 times)
$ end of the string
Another simple solution is this:
^[01]{4}(?<=100|10|1)$
Based on your two possible values [0,1] you only have 8 distinct possibilities:
0000
0001
0010
0011
0100
0101
0110
0111
1111
Your original Regex would hit on all these values. However, the positive look-behind code ensures that the code will either end in '1, '10' or '100'. This covers all possible values except 0000.
The regex:
^(1[01]{3}|01[01]{2}|001[01]|0001)$
Will work and does not rely on look-ahead or look-behind operations which are not, necessarily, available in all regex implementations. Although, now that the question has been edited to provide the languages which will be used: Both PHP and JavaScript regular expressions have negated look-ahead. In those languages, the regex ^(?!0000)[01]{4}$ will work.
The regex at the top of this answer uses multiple terms to build up successively more explicit matches as each character position is specified. The point is that there must be at least one 1 character in the matching four character string. Once a 1 character is encountered in the string, we do not care what the remaining characters are, other than being [01].
The first term 1[01]{3} will match any four 0 and 1 digits that start with 1. This covers all desired matching strings where the first digit is a 1 leaving only desired strings starting with 0 not yet defined as matching.
The second term 01[01]{2} will match any four 0 and 1 digits that start with 01. This leaves only desired strings which start with 00 not yet defined as matching.
The third term 001[01]{2} will match 0010 and 0011
The fourth term 0001 matches the one desired string not matched by the other terms.
Validate an N character long non-zero binary string:
Use a regex comparison and a length check:
Your comments indicate that you have much longer (e.g. 40 characters) similar strings which you need to match in other circumstances.
Given that you have the need to check various different length strings, you are probably best off creating a single function which is able to test multiple different lengths.
In JavaScript, a possibility would be:
function isNonZeroBinaryStringOfLengthN(str, len) {
//True if string is all 0 or 1 with at least one 1 and is the right length.
return (str.length == len && /^[01]*1[01]*$/.test(str) );
}
It is not a good idea to only use the built in functions to parse the string to an integer:
For this circumstance, you are probably best off sticking with a regex based solution rather than using either the PHP intval($str,2) or JavaScript parseInt(str,2). The reason for this is that neither function properly validates the string.
In PHP the command:
echo intval('011134011',2);
prints
7
In JavaScript the command:
console.log(parseInt("0101382730101",2));
prints:
5
This means that if you use one of the internal string->int parsing functions, you still have to separately validate the string you are passing to either function to match ^[01]{n}$. Given that you must to that anyway, you are probably better off using the single regex and length test mentioned above without parsing the string to an int.

Regex for number with decimals and thousand separator

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).

Categories