typeof在输入验证的if语句中失效?求排查JS代码问题(不使用正则)
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:
- Convert the input string to a number.
- Check if that conversion resulted in a valid number (not
NaN). - 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 (returnsNaNif 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 ifNumber(xx)returnsNaN.
内容的提问来源于stack exchange,提问作者Wasiu

