Reputation: 419
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.
Upvotes: 1
Views: 162
Reputation:
Another bad idea :D
/^((?!0(\.0{1,3})?$)[0-4](\.\d{1,3})?|5(\.0{1,3})?)$/
Upvotes: 1
Reputation: 27823
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:
Upvotes: 2
Reputation: 39522
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;
}
}
Upvotes: 3
Reputation: 4666
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
}
Upvotes: 0
Reputation: 784878
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;
}
Upvotes: 2