JavaScript字符串验证工具函数开发遇问题:数字输入验证失效
Hey there! Let's get that string validator working properly. The issue you're seeing with numeric inputs slipping through is likely because your current logic isn't fully enforcing all the validation rules you outlined. Let's break down the solution step by step.
The Exact Validation Rules We Need to Enforce
Let's restate your requirements to make sure we cover every edge case:
- Cannot be
undefined - Cannot be
null - Must be a primitive string type (no numbers, objects, arrays, or wrapper objects like
new String()) - Cannot be an empty string (
'') — must contain at least one character
The Corrected Function
Here's a robust implementation that checks all your boxes:
const isValidString = (str1) => { // Catch undefined or null in one concise check if (str1 == null) { return false; } // Strictly enforce primitive string type (rejects numbers, objects, etc.) if (typeof str1 !== 'string') { return false; } // Ensure the string isn't empty return str1.length > 0; };
Why This Works (And Why Your Old Code Failed)
str1 == null: This is a clean way to reject bothundefinedandnullin a single line (sinceundefined == nullevaluates totrue).typeof str1 !== 'string': This guarantees the input is a primitive string. Numeric values will return'number'fortypeof, objects return'object', arrays return'object'— all of these get blocked here, which fixes your numeric input issue.str1.length > 0: This ensures the string isn't empty. If you also want to reject strings with only whitespace (like' '), modify this line toreturn str1.trim().length > 0;— just note that's an extra check beyond your original requirements.
Test Cases to Verify
Let's run through some examples to confirm it works as expected:
- Valid inputs:
isValidString('hello world')→trueisValidString('!')→trueisValidString(' ')→true(use thetrim()version if you want to reject this)
- Invalid inputs:
isValidString(undefined)→falseisValidString(null)→falseisValidString(123)→falseisValidString({ key: 'value' })→falseisValidString(['array'])→falseisValidString('')→false
Quick note on regex: Regex only works if the input is already a string, so you can't rely on it alone to handle type checks. You need the type validation first — which is probably why your initial regex approach failed with numeric inputs.
内容的提问来源于stack exchange,提问作者Sam

