【发布时间】:2020-02-24 16:12:37
【问题描述】:
这些是我需要检查用户输入的特殊字符、数字和字母 如果用户没有按照以下标准输入,则抛出警报消息。
- (破折号)
- (下划线)
- (句号)
- (
- 空间
- )
- &
- $
- #
- 数字
- 阿尔巴佩特
为此,我在网上的一些文章的帮助下想出了一个正则表达式
我的正则表达式
/^\w\s-.()&$#/
-- Here, \w matches letter , digits and underscores
-- \s matches spaces table and line breaks.
-- - matches the hypen in the character set example [a-z]
示例——str 被传递为
- Name123& ---- 真
- 名字 123$ ---- true
- Name@@@ ---- False,因为 @ 是不允许的
- 名字-._& ---- 真
- Name@._&$ --- 错误,因为 @ 是不允许的
- Name.[] --- 错误,因为 [] 是不允许的
function checkfirmName(str) {
var pattern = new RegExp(/^\w\s-.()&$#/); //acceptable char
if (pattern.test(str)) {
return true; //good user input
}
alert("Please only use \nUnderScore,Dot,(,Space,),&,$,# \nThese are only allowed\n");
return false; // bad user input
}
我也不确定测试扩展是否有效(它返回真假)但不确定它是否遍历并检查每个字符,所以我使用 indexof 找到了另一段代码:
function isValid(str) {
var iChars = "/^\w\s-.()&$#/";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
$.alert("File name has should have special characters \nUnderScore,Dot,(,Space,),&,$,# \nThese are only allowed\n");
return false;
}
}
return true;
}
【问题讨论】:
标签: javascript regex