skip to Main Content

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


  1. It’s because value != "" returns false.

    Replace with not exact equals value !== "" or value != null or value.length > 0 (depends on your usecase)

    Login or Signup to reply.
  2. The value != "" returns false on a 0 (but not on a "0") because of the != operator, which performs type coercion

    Add a toString and use !== not strictly equal

    function isNumericValid(value) {
      var result = false;
      value = value.toString().trim();
      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))
    Login or Signup to reply.
  3. The culprit is clear (the input value should be stringified).

    You function can be reduced to one line:

    console.log(`isNumericValid("0"): ${isNumericValid("0")}`);
    console.log(`isNumericValid(0): ${isNumericValid(0)}`);
    console.log(`isNumericValid("0.0"): ${isNumericValid("0.0")}`);
    console.log(`isNumericValid(0.0): ${isNumericValid(0.0)}`);
    console.log(`isNumericValid(1234.10): ${isNumericValid(1234.10)}`);
    console.log(`isNumericValid("-1234.10"): ${isNumericValid("-1234.10")}`);
    
    function isNumericValid(value) {
      return /^-{0,1}d{1,12}(.d{1,10})?$/.test(String(value).trim());
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search