Jack C Jack C - 17 days ago 4
HTML Question

RegEx says all my inputs are false for a float number (JavaScript)

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;
}

Answer

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.

Comments