-1

My objective is to check if the number that has been input into a form via HTML meets the following...

  • Is a number between 0.01 and 100.0
  • Is a float number e.g. will always of the format 00.01

My RegEx is - "\d{1,3}\.\d{1,2}" - Which when I check on RegExr appears to be correct... http://regexr.com/3eme3

However my code is returning false... Where am I going wrong?

(I've checked it both as a non parsed float number and as a parsed float number)

function checkAgeGrade(){
    var ageGradeValue = document.getElementsByName("AgeGrade")[0].value;
    console.log("Age Grade input: " + ageGradeValue);
    var correctDigits = new RegExp("\d{1,3}\.\d{1,2}");
    console.log("Correct digits: " + correctDigits);

    if(!hasValue(ageGradeValue)){
        document.submitrunnertime.AgeGrade.value = "-1";
    }
    console.log("has a value");

    if(!isNaN(ageGradeValue)){
        console.log("passed isNaN");

        var parsedAgeGradeValue = parseFloat(ageGradeValue);
        console.log(parsedAgeGradeValue);

        if(parsedAgeGradeValue > 0.00 && parsedAgeGradeValue < 100.00){
            console.log("range passed, value is: " + parsedAgeGradeValue + ", checking RegEx");
            console.log("Parsed number: " + correctDigits.test(parsedAgeGradeValue));
            console.log("Not Parsed number: " + correctDigits.test(ageGradeValue));
            return correctDigits.test(parsedAgeGradeValue);
        }
    }
    console.log("false function");
    return false;
}

The function I am using to check to see if the input has a value or not is...

function hasValue(aValue) {
    var whiteSpace = new RegExp("\s+");
    if (aValue.length >= 1) {
        if (whiteSpace.test(aValue)) {
            return false;
        } else {
            return true;
        }
        return false;
    }

1 Answers1

1

Because you're creating your regular expression as a string (which, in this case, is not necessary), you need to double-escape the \d markers. Otherwise, the backslash will be ignored:

var correctDigits = new RegExp("\\d{1,3}\\.\\d{1,2}");

You can also do this:

var correctDigits = /\d{1,3}\.\d{1,2}/;

When you use native regular expression syntax, you don't have to double-escape like you do when the expression is in a string.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thank you - Question: Are the forward slashes "/" required if you are doing a numerical value? –  Nov 17 '16 at 18:23
  • 1
    @JackC The `/.../` a literal regex, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Syntax So yes required. – Andreas Louv Nov 17 '16 at 18:24
  • Ace - Also, is it more desirable to check a RegEx against a String input or a parsedFloat() input? –  Nov 17 '16 at 18:25
  • 1
    @JackC regular expressions really only make sense when inspecting strings. If you parse the string as a number, then you can simply use numeric comparisons to enforce the desired range. – Pointy Nov 17 '16 at 18:29