You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

typeof在输入验证的if语句中失效?求排查JS代码问题(不使用正则)

Why Your typeof Check Isn't Working for Input Validation

Hey there! Let's break down why that typeof condition in your code isn't triggering like you expect.

The Core Issue: Input Values Are Always Strings

Here's the key detail you might have missed: any value pulled from an input element's .value property is always a string—no matter what the user types. Even if someone enters 123, document.getElementById('demo').value will return the string "123", not a numeric type.

That means your check if(typeof xx === "number") will never be true. typeof "123" is always "string", so that throw statement never runs.

Fixing It Without RegExp

Since you don't want to use regular expressions, here's how you can properly detect if the input is a numeric value:

  1. Convert the input string to a number.
  2. Check if that conversion resulted in a valid number (not NaN).
  3. Optional: Verify the input was a pure numeric string (to avoid edge cases like "123abc").

Here's your updated code with these fixes:

function myDom(){ 
  var message = document.getElementById('show'); 
  var xx = document.getElementById('demo').value.trim(); // Trim whitespace to catch empty inputs with spaces
  try{ 
    if(xx === "") throw "can not be empty"; 
    // Convert input to a number
    const parsedNumber = Number(xx);
    // Check if the conversion gave us a valid number
    if(!isNaN(parsedNumber)) {
      // Optional: Ensure input was a pure numeric string (no extra characters)
      if(xx === parsedNumber.toString()) {
        throw "can not be number";
      }
    }
    // Uncomment if you want to add the <100 check
    // if(parsedNumber < 100 && !isNaN(parsedNumber)) throw "less than hundreds!" 
  }catch(err){ 
    message.innerHTML = "input " + err; 
  } 
}

Quick Explanation of the Fix

  • xx.trim(): Catches cases where the user enters only spaces (which would otherwise pass the empty check).
  • Number(xx): Converts the string input to a number (returns NaN if the input isn't numeric).
  • !isNaN(parsedNumber): Checks if the conversion worked (i.e., the input was a valid numeric value).
  • xx === parsedNumber.toString(): Ensures the input didn't have extra non-numeric characters (like "123a"), which would fail this check even if Number(xx) returns NaN.

内容的提问来源于stack exchange,提问作者Wasiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:54:07