Regular Expression in JS for numbers - javascript

I'm looking for a regular expression in javascript that takes care of this:
Accept only numbers between 6 and 15 digits, 6 is the minimum.
Numbers cannot contain groups of repeated digits, such as 408408 or 123123
Numbers cannot contain only two different digits, such as 121212
I started with this, then I was loss
^[0-9]{6,15}$

Instead of just a Regex, use a combination of if-statements and a RegEx.
function validateNumber() {
var numbers = document.getElementById('numbers1').value;
if (numbers && !isNaN(numbers)) {
// make sure a that something was entered and that it is a number
if (numbers.length < 6 || numbers.length > 15) {
// make sure number is between 6 and 15 digits
alert('Number must be between 6 and 15 digits long.');
} else if (numbers.match(/(.+)\1+/)) {
// make sure that the numbers contain no repeated digits
alert('Number cannot be repeated.');
} else {
alert('Number validated!');
// otherwise, the number is validated
}
} else {
// if no number was entered
alert('Please enter a number.');
}
}
<input type="text" placeholder="enter numbers" id="numbers1" />
<input type="button" value="Validate!" onclick="validateNumber()" />

You have the first rule correct:
^\d{6,15}$
That covers both the 6-15 length requirement and the fact that it has to be numeric.
With the next rule, it's easier to test for repeated substrings than to test for their absence:
(.+)\1
The last one is a lot more complicated. Here's how you test for at least 3 distinct characters:
(.+)(?!\1)(.+)(?!\1|\2).
Put it all together and what do you get:
^(?=\d{6,15}$)(?!.*(.+)\1)(.+)(?!\2)(.+)(?!\2|\3).+$
That answers your question as written, but as I said in the comments, you should consider very carefully whether you're starting from the right assumptions. You don't have to use regex for this, nor do you have to do it all in one regex. Will the pattern above be easy for you to work with when you come back in 6 months and have to change the rules?
More importantly, if you're trying to make sure users pick a strong password, the rules you're using will weaken your security by reducing the number of possible choices. And the maximum length of 15 characters suggests you're storing passwords in plain text. You should be hashing them.

Here's my attempt, just for the challenge:
^(?!\d*?(\d+?)\1)\d{6,15}$
Demo
The (?!\d*?(\d+?)\1) part will make sure there are no groups of repeated digits by matching a group of digits and trying to match the same digits immediately after. If it finds one, the match fails.
If you want to allow two same consecutive digits, replace (?!\d*?(\d+?)\1) with (?!\d*?(\d{2,}?)\1)(?!(\d)\2*(\d)(?:\2|\3)*$). This will then make sure there are more than 2 different digits by matching a series of one digit, then a different digit followed by a series of a combination of both digits. If it reaches the end of the string it forces the match to fail.
But it'll be probably more maintainable to just do it the conventional way, without regex.

Related

JavaScript Regex not matching mobile number with international code

Am trying to validate a mobile number 254777123456 against a regex /^((254|255)[0-9]+){9,15}$/, the mobile number should be prefixed with the country codes specified but the total length of the mobile number should not be more than 15 characters, doing this via javascript am getting null, can anyone point out what am doing wrong.
PS. Am using way more country codes than the ones I specified, I just put those two as a test before I add the others because they will all be separated by the pipe.
Your regex ^((254|255)[0-9]+){9,15}$ means, that pick at least 4 digits (of which first 3 should be either 254 or 255) and whole of them must occur at least 9 times to max 15 times, which will mean the minimum length of string that will match should be of 36 characters. Which obviously you don't want. Your regex needs little correction where you need to take [0-9] part out and have {9,12} quantifier separately. Correct regex to be used should be this,
^(?:(?:254|255)[0-9]{9,12})$
This regex will match 254 or 255 separately and will restrict remaining number to match from 9 to 12 (as you want max number to be matched of length 15 where 3 numbers we have already separated out)
Demo
var nums = ['254777123456','255777123456','255777123456123','2557771234561231']
for (n of nums) {
console.log(n + " --> " + /^(?:(?:254|255)[0-9]{9,12})$/g.test(n));
}

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

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

what's wrong with this regular expression (if else regex)

What I want is, there is a textbox with maximum length of 5. The values allowed are..
any integer // for example 1, 3, 9, 9239 all are valid
real number, with exaclty one point after decimal // eg. 1.2, 93.7 valid and 61.37, 55.67 invalid
it is also allowed to enter only decimal and a digit after that, that is .7 is valid entry (would be considered as 0.7)
I found this page, http://www.regular-expressions.info/refadv.html
So what I thought is that
There is a digit
If there is a digit and a decimal after that, there must be one number after that
If there is no digit there must be a decimal and a digit after that
So, the regex I made is..
a single digit one or more => /d+
an optional decimal point followed by exactly one digit => (?:[.]\d{1})?
if first condition matches => (?(first condition) => (?((?<=\d+)
then, match the option decimal and one exact digit =>(?((?<=\d+)(?:[.]\d{1})?
else => |
find if there is a decimal and one exact digit => (?:[.]\d{1}){1}
check the whole condition globally => /gm
overall expression =>
(?(?<=\d+)(?:[.]\d{1}){1}|(?:[.]\d{1}){1})+/gm
But it doesn't outputs anything..
Here's the fiddle
http://jsfiddle.net/Fs6aq/4/
ps: the pattern1 and pattern2 there, are related to my previous question.
Maybe you are complicating things too much. I did a quick test and unless I'm missing something this regex seems to work fine:
/^\d*\.?\d$/
Demo: http://jsbin.com/esihex/4/edit
Edit: To check the length you can do it without regex:
if ( value.replace('.','').length <= 5 && regex.test( value ) ) {
...
}
Notice that I used replace to remove the dots so they don't count as characters when getting the length.
You can try the following pattern:
/^\d{0,4}\.?\d$/
It seems to fulfil all your requirements:
> /^\d{0,4}\.?\d$/.test(".4")
true
> /^\d{0,4}\.?\d$/.test(".45")
false
> /^\d{0,4}\.?\d$/.test("1234.4")
true
> /^\d{0,4}\.?\d$/.test("12345.4")
false
> /^\d{0,4}\.?\d$/.test("12345")
true
> /^\d{0,4}\.?\d$/.test("123456")
false
This pattern assumes that the number can have a maximum of five digits and an optional decimal point.
If the maximum length of five includes the optional decimal point then the pattern is slightly more complex:
/^(?:\d{1,5}|\d{0,3}\.\d)$/
The first part of the group deals with integer numbers of the required length, the second option of the group deals with real numbers which maximum length (including the decimal point) is five.
Consider this code:
var checkedString = "45.3 fsd fsd fsdfsd 673.24 fsd63.2ds 32.2 ds 32 ds 44 fasd 432 235f d653 dsdfs";
checkedString = " "+checkedString;
var results = checkedString.match(/[\s]{1}(\d+\.*\d{1})(?![\d\.\w])+/gm);
results.map(function(result) {
return result.trim();
});
Couldn't make it in other way because in JS (?<= (lookbehind) regexp is not working.
This will be returned:
["45.3","32.2","32","44","432"]
So probably it's what you've expected.
I don't know what are you trying to do with those conditionals in your regex. I also looked at your jsfiddle, which outputs nothing for me. But I made a two versions of a regex that matches the correct values for the textbox, which are ^(?!(.{6,}))(?:[1-9]\d*)*(?:\.\d*[1-9])?$ and ^(?!(.{6,}))(?:\d*)*(?:\.\d*)?$.
The first disallows to start with zero, or end with zero after the decimal.
Comment if you need explanation of the regex.

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