我试图允许输入中文或字母字符。
var name="TEXT" //here input either alphabetic or Chinese Characters 请输入
let reqChinesePos=/^[\u3000\u3400-\u4DBF\u4E00-\u9FFF]\d{8}$/;
let reqEnglish=/^[A-Za-z]\d{40}$/
console.log(reqEnglish.test(name)); //Here true but here also Chinese characters also match.
console.log(reqChinesePos.test(name)); //Here true but here also alphabetic characters also match.
预期结果:
console.log(reqEnglish.test(name));//here only allow alphabetic characters not allow chinese.
console.log(reqChinesePos.test(name));//here only allow Chinese characters not allow English.
答案 0 :(得分:1)
您的汉字字符类范围似乎是正确的,至少从这里的简单本地测试来看。但是,我发现这两种模式都存在另一个问题,如果您想同时在两种情况下都允许使用罗马数字,则\d
可能应该是字符类的一部分。进行此更改后,然后为输入指定宽度或宽度范围。假设您希望两者的宽度都为8,则可以尝试:
var reqChinesePos = /^[\u3000\u3400-\u4DBF\u4E00-\u9FFF\d]{8}$/;
var reqEnglish = /^[A-Za-z\d]{8}$/
var name1 = "大猫大猫大猫大猫";
var name2 = "JONATHAN";
var name3 = "BIGCAT大猫";
console.log(name1);
console.log(reqEnglish.test(name1));
console.log(reqChinesePos.test(name1));
console.log(name2);
console.log(reqEnglish.test(name2));
console.log(reqChinesePos.test(name2));
console.log(name3);
console.log(reqEnglish.test(name3));
console.log(reqChinesePos.test(name3));