I have this JavaScript function in my Razor page to check if the value is numeric.
When a "0" is passed to this function, it will return as false. I have tested the expression in other RegEx tester and "0" is a valid match. If the input parameter is "0.0", it will be ok.
Any idea what went wrong? Please advise. Thanks.
function isNumericValid(value) {
var result = false;
if (value != "") {
// up to 12 digits and 10 dec places
let template = /^-{0,1}d{1,12}(.d{1,10})?$/;
if (template.test(value))
result = true;
}
return result;
}
console.log(isNumericValid("0"))
console.log(isNumericValid(0))
console.log(isNumericValid("0.0"))
console.log(isNumericValid(0.0))
console.log(isNumericValid(1234.10))
3
Answers
It’s because
value != ""
returns false.Replace with not exact equals
value !== ""
orvalue != null
orvalue.length > 0
(depends on your usecase)The
value != ""
returns false on a0
(but not on a"0"
) because of the!=
operator, which performs type coercionAdd a toString and use
!==
not strictly equalThe culprit is clear (the input value should be stringified).
You function can be reduced to one line: