如何在JavaScript中验证希腊字符?修改正则后无效果求解决
Let's break down why your modified regex isn't working as expected and get it sorted out.
First, the root issue with your current pattern: [^A-Za-z\\u0391-\\u03C9\\s]
The range \u0391-\u03C9 only covers uppercase Greek letters (Α to Ω) and the lowercase Omega (ω)—it misses all other lowercase Greek letters (α to ψ, which fall in the \u03B1 to \u03C8 range). That's why lowercase Greek characters are still being flagged as invalid.
Solution 1: Fix the Character Range (Works in All JS Environments)
Update your regex to include complete uppercase and lowercase Greek letter ranges:
case "alpha_s": { ret = TestInputType(objValue, "([^A-Za-z\\u0391-\\u03A9\\u03B1-\\u03C9\\s])", strError, objValue.name + ": Only alphabetic characters, Greek letters and space allowed "); break; }
\u0391-\u03A9: Covers all standard uppercase Greek letters (Α to Ω)\u03B1-\u03C9: Covers all standard lowercase Greek letters (α to ω)
Solution 2: Use Unicode Property Classes (Modern & Comprehensive)
If your JavaScript environment supports ES2018+ (most modern browsers and Node.js versions do), use a Unicode property class to match all Greek script characters in one go. This is cleaner and automatically covers edge cases like accented Greek letters:
case "alpha_s": { ret = TestInputType(objValue, "([^A-Za-z\\p{Script=Greek}\\s])", strError, objValue.name + ": Only alphabetic characters, Greek letters and space allowed "); break; }
Critical note: For this to work, your TestInputType function must create the regex with the u (Unicode) flag. Inside that function, the regex initialization should look like:
function TestInputType(value, pattern, errorMsg, ...rest) { const regex = new RegExp(pattern, 'u'); // Add the 'u' flag here // Rest of your validation logic... }
The \p{Script=Greek} property matches any character tied to the Greek writing system, making it more robust than manually defining character ranges.
内容的提问来源于stack exchange,提问作者user3102627

