Regex for 1-10 in javascript for validation - javascript

What would be the regex for numbers ranging 1-10 and 1-5? Please help this troubled soul.

You could achive that with easy number checks in javascript:
// Convert input to integer just to be sure
mynum = parseInt(mynum, 10);
// Check number-range
if(mynum >= 1 && mynum <=10)
and
if(mynum >= 1 && mynum <=5)
If you really want to use regex:
/^([1-9]|10)$/
and
/^[1-5]$/
UPDATE:
Fixed the first regex to correctly match the string boundings
Added parseInt to the first example to ensure correct number-checks

This is not a good use of Regular Expressions.
Use simple conditions:
if (x > 0 && x < 6) {
// x is 1 - 5
}
if (x > 0 && x < 10) {
// x is 1 - 10
}

For 1-5 you only need to enclose it as character class:
/^[1-5]$/
For 1-10 you'd just need an additional alternative:
/^([1-9]|10)$/

Is there a reason you want to use regular expressions?
/([1-9]|10)/

Use numeric comparison. The following Number extension can check if a number falls between 2 values:
Number.prototype.between =
function(lower,upper, includeBoundaries){
lower = Number(lower);
upper = Number(upper);
noCando = isNaN(lower) ||
isNaN(upper) ||
lower>=upper;
if ( noCando ) {
throw 'wrong arguments or out of range';
}
return includeBoundaries
? this >= lower && this <= upper
: this > lower && this < upper
};
// usage:
(12).between(1,12); /=> false
(12).between(1,12,true); /=> true
(12).between(0,15,true); /=> true
(0).between(-5,1); //=> true
The function converts the parameters to Number because 0 can evaluate to a boolean in javascript, to be able to check if the paramaters are real number values and to be able to check if lower is not greater than/equal to upper. In those cases an error is thrown.
The includeBoundaries parameter also checks if a Number is equal to lower or upper, if it's not supplied, the function returns a real 'between'-check.

For 1-10 it can be
/^([1-9]|10)$/
and for 1-5 simply
/^[1-5]$/

The answer would be
/^([1-9]|10)$/

Related

getting wrong answer for finding largest of 2 numbers using readline-sync in js [duplicate]

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

Write program that uses a while loop to get first and last numbers from the string, calculate the sum, removing these numbers then doing it again [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
DON'T FORGET - Use parseFloat(); if your dealing with decimals.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
This also works for you:
dots -= -5;
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.
UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;

How to create regex for passwords validate with length 8 - 24 and contain at least 3 of the following: lowercase, uppercase, numbers, special char

I want to use java-script to validate following criteria for password.
a.A password of at least 8 and no more than 24 characters is required.
b.Every password must contain at least three of these four types of characters:
1.an upper case letter
2.a lower case letter
3.a number
4.a special character.
I have found this code which is really easy and hand-full but it is just checking all 4 conditions not just at-least 3 conditions out of 4.
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,24}"
I will really appreciate if you help me to figure out to create javascript validation on password to full fill my above requirement.
Thank you all for your help. I have modified #Ehtesham code and achieved the functionality.
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
var count = 0;
if (pass.length < 8 || pass.length > 24) {
return false;
}
if (pass.match(lowerRegex)){count += 1;}
if (pass.match(upperRegex)){count += 1;}
if (pass.match(numberRegex)){count += 1;}
if (pass.match(specialRegex)){count += 1;}
if (count >= 3){
return true;
}else{
return false;
}
}
The regex you provided is made out of 5 major parts:
The pattern validating the length: [A-Za-z\d$#$!%*?&]{8,24}
A positive lookahead for at least one lowercase: (?=.*[a-z])
A positive lookahead for at least one uppercase: (?=.*[A-Z])
A positive lookahead for at least one number: (?=.*\d)
A positive lookahead for at least one special char: (?=.*[$#$!%*?&])
Now, you only want to apply 3 out of the 4 positive lookaheads. Since lookaheads are non-consuming matches, the cursor of the regex-engine will remain unchanged, as the matching is going on. (Using positive Lookaheads this way is often used to generate AND-Patterns)
So, you now have 4 conditions and you want that only 3 of them are matched. As described, it would be easy to use independent expressions and check if 3 apply. However, some native features (for instance jsf's f:validateRegex) only work with a single pattern.
Regular Expressions are supporting OR in a native way: | - hence to turn your expression 1 AND 2 AND 3 AND 4 into a minimum requirement of matching 3 of them, you could use an expression like (1 AND 2 AND 3) OR (1 AND 2 AND 4) OR (1 AND 3 AND 4) OR (2 AND 3 AND 4), which would cover all usecases required:
1 2 3 4
1 1 1 0
1 1 0 1
1 0 1 1
0 1 1 1
So, to match all this within a single pattern, just rearange your lookaheads as required:
^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])|(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&])|(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]))[A-Za-z\d$#$!%*?&]{8,24}$
Drilldown:
^(?: - non matching group
(?=.*[a-z])(?=.*[A-Z])(?=.*\d) - one lower, one upper, one number
| - or
(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&]) - one lower, one upper, one special
| - or
(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&]) - one lower, one number, one special
| - or
(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]) - one upper, one number, one special
)
[A-Za-z\d$#$!%*?&]{8,24}$ - 8 to 24 chars.
(Debuggex is using javascript)
^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])|(?=.*[a-z])(?=.*\d)(?=.*[$#$!%*?&])|(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&]))[A-Za-z\d$#$!%*?&]{8,24}$
Debuggex Demo
Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference. There is a password validation entry under
"Common validation tasks > Internet"
That said, this seems like a pretty easy task if you break it up, as others have suggested. Mashing up all those requirements into a single regex, although an interesting exercise, is overkill in my opinion.
(This is Java, but there are equivalent concepts in JavaScript.)
public bolean isPasswordValid(String password) {
if(!length in bounds) {
return false;
}
boolean hasUpper = Pattern.compile("[a-z]").find(password);
boolean hasLower = Pattern.compile("[A-Z]").find(password);
boolean hasDigit = Pattern.compile("[0-9]").find(password);
boolean hasSpecialChar = Pattern.compile("...NOT SURE OF THIS ONE...").find(password);
int types = (hasUpper ? 1 : 0) + (hasLower ? 1 : 0) +
(hasDigit ? 1 : 0) + (hasSpecialChar ? 1 : 0);
return (types >= 3);
}
And if this is a function that will be used rapid fire, then you'll likely want to pre-compile and store those Matchers.
In javascript you can use following simple function.
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
if (pass.length < 8 || pass.length > 24) {
return false;
}
if (pass.match(lowerRegex) && pass.match(upperRegex) &&
pass.match(numberRegex) && pass.match(specialRegex)) {
return true;
}
return false;
}
Jsfiddle demo
This builds on Ehtesham's answer to require 3 out of 4:
function isValidPassword(pass) {
var lowerRegex = /[a-z]/;
var upperRegex = /[A-Z]/;
var numberRegex = /[0-9]/;
var specialRegex = /[$#$!%*?&]/;
var mustBe3 = 0;
if(pass.length < 9 || pass.length > 24) { return false; }
if(pass.match(lowerRegex)) { mustBe3 ++; }
if(pass.match(upperRegex)) { mustBe3 ++; }
if(pass.match(numberRegex)) { mustBe3 ++; }
if(pass.match(specialRegex)){ mustBe3 ++; }
// for testing ...
if(window.console) console.log('pass: '+pass+' mustBe3: '+mustBe3);
if( mustBe3 >= 3 ) { return true; }
return false;
}

Javascript regex for amount

I'm trying to get a regex for an amount:
ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])
What I have is:
/^\d+\.\{0,1}+\d{0,2)+$/
...obviously not working. Examples of what I'm trying to do:
123 valid
123.00 valid
12.34.5 invalid
123.000 invalid
Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.
Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:
/^\d+(\.\d{1,2})?$/
Tests:
> var re = /^\d+(\.\d{1,2})?$/
undefined
> re.test('123')
true
> re.test('123.00')
true
> re.test('123.')
false
> re.test('12.34.5')
false
> re.test('123.000')
false
Have you tried:
/^\d+(\.\d{1,2})?$/
The ? makes the group (\.\d{1, 2}) optional (i.e., matches 0 or 1 times).
Would something like this work?
// Check if string is currency
var isCurrency_re = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
return String(s).search (isCurrency_re) != -1
}

What does ~~ ("double tilde") do in Javascript?

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would give back the same value, wouldn't it?
It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number.
In other words, it yields:
function(x) {
if(x < 0) return Math.ceil(x);
else return Math.floor(x);
}
only if x is between -(231) and 231 - 1. Otherwise, overflow will occur and the number will "wrap around".
This may be considered useful to convert a function's string argument to a number, but both because of the possibility of overflow and that it is incorrect for use with non-integers, I would not use it that way except for "code golf" (i.e. pointlessly trimming bytes off the source code of your program at the expense of readability and robustness). I would use +x or Number(x) instead.
How this is the NOT of the NOT
The number -43.2, for example is:
-43.210 = 111111111111111111111111110101012
as a signed (two's complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:
NOT -4310 = 000000000000000000000000001010102 = 4210
Inverting again gives:
NOT 4210 = 111111111111111111111111110101012 = -4310
This differs from Math.floor(-43.2) in that negative numbers are rounded toward zero, not away from it. (The floor function, which would equal -44, always rounds down to the next lower integer, regardless of whether the number is positive or negative.)
The first ~ operator forces the operand to an integer (possibly after coercing the value to a string or a boolean), then inverts the lowest 31 bits. Officially ECMAScript numbers are all floating-point, but some numbers are implemented as 31-bit integers in the SpiderMonkey engine.
You can use it to turn a 1-element array into an integer. Floating-points are converted according to the C rule, ie. truncation of the fractional part.
The second ~ operator then inverts the bits back, so you know that you will have an integer. This is not the same as coercing a value to boolean in a condition statement, because an empty object {} evaluates to true, whereas ~~{} evaluates to false.
js>~~"yes"
0
js>~~3
3
js>~~"yes"
0
js>~~false
0
js>~~""
0
js>~~true
1
js>~~"3"
3
js>~~{}
0
js>~~{a:2}
0
js>~~[2]
2
js>~~[2,3]
0
js>~~{toString: function() {return 4}}
4
js>~~NaN
0
js>~~[4.5]
4
js>~~5.6
5
js>~~-5.6
-5
In ECMAScript 6, the equivalent of ~~ is Math.trunc:
Returns the integral part of a number by removing any fractional digits. It does not round any numbers.
Math.trunc(13.37) // 13
Math.trunc(42.84) // 42
Math.trunc(0.123) // 0
Math.trunc(-0.123) // -0
Math.trunc("-1.123")// -1
Math.trunc(NaN) // NaN
Math.trunc("foo") // NaN
Math.trunc() // NaN
The polyfill:
function trunc(x) {
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
The ~ seems to do -(N+1). So ~2 == -(2 + 1) == -3 If you do it again on -3 it turns it back: ~-3 == -(-3 + 1) == 2 It probably just converts a string to a number in a round-about way.
See this thread: http://www.sitepoint.com/forums/showthread.php?t=663275
Also, more detailed info is available here: http://dreaminginjavascript.wordpress.com/2008/07/04/28/
Given ~N is -(N+1), ~~N is then -(-(N+1) + 1). Which, evidently, leads to a neat trick.
Just a bit of a warning. The other answers here got me into some trouble.
The intent is to remove anything after the decimal point of a floating point number, but it has some corner cases that make it a bug hazard. I'd recommend avoiding ~~.
First, ~~ doesn't work on very large numbers.
~~1000000000000 == -727279968
As an alternative, use Math.trunc() (as Gajus mentioned, Math.trunc() returns the integer part of a floating point number but is only available in ECMAScript 6 compliant JavaScript). You can always make your own Math.trunc() for non-ECMAScript-6 environments by doing this:
if(!Math.trunc){
Math.trunc = function(value){
return Math.sign(value) * Math.floor(Math.abs(value));
}
}
I wrote a blog post on this for reference: http://bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html
Converting Strings to Numbers
console.log(~~-1); // -1
console.log(~~0); // 0
console.log(~~1); // 1
console.log(~~"-1"); // -1
console.log(~~"0"); // 0
console.log(~~"1"); // 1
console.log(~~true); // 1
console.log(~~false); // 0
~-1 is 0
if (~someStr.indexOf("a")) {
// Found it
} else {
// Not Found
}
source
~~ can be used as a shorthand for Math.trunc()
~~8.29 // output 8
Math.trunc(8.29) // output 8
Here is an example of how this operator can be used efficiently, where it makes sense to use it:
leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),
Source:
See section Interacting with points
Tilde(~) has an algorihm -(N+1)
For examle:
~0 = -(0+1) = -1
~5 = -(5+1) = -6
~-7 = -(-7+1) = 6
Double tilde is -(-(N+1)+1)
For example:
~~5 = -(-(5+1)+1) = 5
~~-3 = -(-(-3+1)+1) = -3
Triple tilde is -(-(-(N+1)+1)+1)
For example:
~~~2 = -(-(-(2+1)+1)+1) = -3
~~~3 = -(-(-(3+1)+1)+1) = -4
Same as Math.abs(Math.trunc(-0.123)) if you want to make sure the - is also removed.
In addition to truncating real numbers, ~~ can also be used as an operator for updating counters in an object. The ~~ applied to an undefined object property will resolve to zero, and will resolve to the same integer if that counter property already exists, which you then increment.
let words=["abc", "a", "b", "b", "bc", "a", "b"];
let wordCounts={};
words.forEach( word => wordCounts[word] = ~~wordCounts[word] + 1 );
console.log("b count == " + wordCounts["b"]); // 3
The following two assignments are equivalent.
wordCounts[word] = (wordCounts[word] ? wordCounts[word] : 0) + 1;
wordCounts[word] = ~~wordCounts[word] + 1;

Categories