html - RegEx says all my inputs are false for a float number (JavaScript) -
this question has answer here:
my objective check if number has been input form via html meets following...
- is number between 0.01 , 100.0
- is float number e.g. of format 00.01
my regex - "\d{1,3}\.\d{1,2}
" - when check on regexr appears correct... http://regexr.com/3eme3
however code returning false... going wrong?
(i've checked both non parsed float number , 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 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 using check see if input has 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; }
because you're creating regular expression string (which, in case, not necessary), need double-escape \d
markers. otherwise, backslash ignored:
var correctdigits = new regexp("\\d{1,3}\\.\\d{1,2}");
you can this:
var correctdigits = /\d{1,3}\.\d{1,2}/;
when use native regular expression syntax, don't have double-escape when expression in string.
Comments
Post a Comment