user3066033
user3066033

Reputation: 419

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.

Upvotes: 1

Views: 162

Answers (5)

user1636522
user1636522

Reputation:

Another bad idea :D

/^((?!0(\.0{1,3})?$)[0-4](\.\d{1,3})?|5(\.0{1,3})?)$/

http://regex101.com/r/kV5qK0

Upvotes: 1

Tibos
Tibos

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:

  • 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

Upvotes: 2

h2ooooooo
h2ooooooo

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

i100
i100

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

anubhava
anubhava

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

Related Questions