Javascript regex for amount - javascript

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
}

Related

JS Validate Crossword Clue Enumeration

I need to validate a crossword clue's enumeration (the number(s) in the brackets). For example, "Big star (3,5)" - the enumeration is 3,5.
I'm struggling with the required regular expression. Rules should be as follows:
only allow characters 0-9, hyphens and commas
each number shouldn't start with a zero e.g. "09" should be just "9"
it should start with a number
it should end with a number
it shouldn't allow repeated hyphens/commas e.g "3,,5" or "3--5" or "3,-5" or 3-,5"
Some VALID examples...
1
1,2
1,2-3
1,2-3,4
Some INVALID examples...
text
-1
1,
1,,2
0-1
3-04
Hopefully you get the idea. Any help would be greatly appreciated.
Regular expressions are very powerful but can be a pain to write out sometimes, especially if you don't use them often. This is why I often use this site to help.
After speaking in the comments, a logic error became apparent: the regexp would not match anything with 0, even if it did not start with it. It would also not match numbers without - like just 10.
Now, I came up with ([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+)?) but there was another problem:
10-5-40 would be matched as expected
but the 3-2 in 03-2 and the 3 and 2 in 03-02 would also be matched.
So I included some JS logic in addition to the RegExp. Hopefully now it works as intended.
let Regexp1 = /([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+)?)/;
let Regexp2 = /([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+))/;
function test(t) {
match1 = (t.match(Regexp1) != null);
match2 = (t.match(Regexp2) != null);
let matches = false;
if(match1 && match2) {
matches = true;
} else if(match1 && !match2) {
if(t.match(Regexp1)[0].length == t.length) {
matches = true;
} else {
matches = false;
}
}
if(t.match(Regexp1)[0].length != t.length) {
matches = false;
}
console.log(matches);
return matches;
}
test("10-5"); // true
test("03-4"); // false
test("0-5"); // false
test("1,05"); // false
test("1--5"); // false
test("10"); // true
test("10-05"); // false

Correct joining of this regex for password confirmation

Trying to create a jquery function that checks if the password meets the certain requirments, password must contain at least 3 characters being uppercase, numbers or special characters. This can be a mix of the 3, so could be 2 uppercase and 1 special etc....
I have created a function which checks using regex but its very long, I know it can be joined together but I cant seem to figure out how.
$('#Password').blur(function () {
var pswd = $(this).val();
if (pswd.length > 7) {
if (pswd.match(/(?=(.*[A-Z].*){3,}).{7,}/) // 3 caps
||
pswd.match(/(?=(.*\W.*){3,}).{7,}/) // 3 special chars
||
pswd.match(/(?=(.*\d.*){3,}).{7,}/) // 3 digits
||
(pswd.match(/(?=(.*[A-Z].*){2,})/ && pswd.match(/(?=(.*\W.*){1,})/))) // 2 caps 1 special
||
(pswd.match(/(?=(.*[A-Z].*){1,})/ && pswd.match(/(?=(.*\W.*){2,})/))) // 1 cap 2 special
||
(pswd.match(/(?=(.*[A-Z].*){2,})/ && pswd.match(/(?=(.*\d.*){1,})/))) // 2 cap 1 digit
||
(pswd.match(/(?=(.*[A-Z].*){1,})/ && pswd.match(/(?=(.*\d.*){2,})/))) // 1 cap 2 digit
||
(pswd.match(/(?=(.*\W.*){2,})/ && pswd.match(/(?=(.*\d.*){1,})/))) // 2 special 1 digit
||
(pswd.match(/(?=(.*\W.*){1,})/ && pswd.match(/(?=(.*\d.*){2,})/))) // 1 special 2 digit
||
(pswd.match(/(?=(.*\W.*){1,})/ && pswd.match(/(?=(.*\d.*){1,})/) && pswd.match(/(?=(.*[A-Z].*){1,})/)))
) // 1 of each /
{
$('#Message').hide();
}
} else {
$('#Message').show();
}
});
The function works fine but I want to improve the regex, is it possible to do the same password check in better time or reduction of code.
What about if you count the special character occurrence in the string, like:
pswd.match(/(?=[A-Z])|(?=[0-9])|(?=[#$^+=!*()#%&])/g).length
...and compare with '3' in your case.
#PJProudhon - Thanks for the suggestion:
pswd.match(/[A-Z]|[0-9]|[#$^+=!*()#%&]/g).length
Focus on "must contain at least 3 characters being uppercase, numbers or special characters".
You can express it as: contains at least 3 characters which are not lower case. That way no join is even needed here.
I'll give a try to ^(?=(?:[a-z]*[^a-z]){3}).{7,}$.

How to check if a string is a positive integer, allowing 0 and all-0 decimals

So to check if a string is a positive integer, I have done some research and found this solution here by someone:
Validate that a string is a positive integer
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
However, I put this into test, and found that numbers with pure 0's on the decimal places does not seem to be working. For example:
15 ===> Works!
15.0 ====> Does not work :(
15.000 ===> Does not work :(
Build upon the existing method, how could I allow pure-0's on the decimal places and make them all work? Please note 15.38 should not work, but 15.00 should.
No need to use regex here.
function isNormalInteger(str) {
var n = parseInt(str);
return n > 0 && n == +str;
}
Then test it:
isNormalInteger(15)
true
isNormalInteger(15.00)
true
isNormalInteger(15.38)
false
isNormalInteger(-15)
false
isNormalInteger(-15.1)
false
First of all the function should be called isNormalNumber instead of isNormalInteger as it accepts decimals, then this is the REgex you need:
function isNormalNumber(str) {
return /^\+*[0-9]\d*(\.0+)?$/.test(str);
}
alert(isNormalNumber("+10.0") + "::" + isNormalNumber("+10.9") + "::" + isNormalNumber("10"));
Returns true::false:true.
EDIT:
This is an edit to avoid matching leading zeros like in the numbers 001234 and 07878:
^\+*[1-9]\d*(\.0+)?$|^0(\.0+)?$
Quick and dirty
function isNormalInteger(str) {
var ival=parseInt(str);
return ival!=NaN && ival>=0 && ival==parseFloat(str);
}

regex validation in javascript

Question:
Maximum of 5 characters (0.000 < courier weight <=5.000 with max of 3 digits after decimal point)
Values can be between 0 and 5. Excluding 0 and including 5.
My codes:
function checkWeightOfParcel(weightOfParcel) {
var regex=/^[0-5]+\.[0-9]$/;
if(regex.test(weightOfParcel)) {
alert('correct!!!')
return true;
}
else {
alert('wrong regex!')
return false;
}
}
*my code only can validate range 0.000 to 5.999, it is wrong. How to remove 0.999 behind to set the max value is 5.000
Any website or forum to learn javascript regex? i'm new to it, thanks for help.
No reason to use regex for this. Parse it to a number using parseFloat, and then use simple conditions:
function checkWeightOfParcel(weightOfParcel) {
//Turn it into a number
weightOfParcel = parseFloat(weightOfParcel);
if (weightOfParcel > 0 && weightOfParcel <= 5) {
alert('correct!!!')
return true;
}
else {
alert('wrong regex!')
return false;
}
}
You shouldn't be using regex to do this. Simple code check like this is suffice:
if(weightOfParcel > 0 && weightOfParcel <= 5) {
alert('correct!!!')
return true;
}
else {
alert('wrong value!')
return false;
}
While you shouldn't use regexp for this, here is one that works:
/^(?:(?:[1-4](?:\.\d{1,3})?)|(?:5(?:\.0{1,3})?)|(?:0\.(?:(?:(?:[1-9]\d{0,2}))|(?:0[1-9]\d?)|(?:00[1-9]))))$/
A site that is great for trying out and understanding regex is this one (already filled with your regex):
http://regex101.com/r/cM6xC9
Basically, i split your cases in two:
Numbers starting with 1,2,3,4 which may be followed by a . followed by 1,2 or 3 decimals.
Numbers starting with 5 which may be followed by a . followed by 1,2 or 3 zeroes.
Numbers starting with 0 which must be followed by a . followed by
non zero digit followed by 0-2 more digits
0 followed by non zero digit followed by 0-1 more digits
00 followed by non zero digit
Another bad idea :D
/^((?!0(\.0{1,3})?$)[0-4](\.\d{1,3})?|5(\.0{1,3})?)$/
http://regex101.com/r/kV5qK0
Why are you using regex? it is easier to compare numbers.
function checkWeightOfParcel(weightOfParcel) {
// var weightOfParcel = parseFloat(weightOfParcel); // to avoid double parsing
return parseFloat(weightOfParcel) < 0 || parseFloat(weightOfParcel) > 5
}

Regex for 1-10 in javascript for validation

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)$/

Categories