javascript - 验证表单时如何检查特殊字符
问题描述
我正在尝试将表单验证添加到我的表单中。我已经设法对字符长度、数字、字母进行了处理,并且它们都可以正常工作,但它似乎不适用于特殊字符,例如 @ & * 等。
我已经尝试按照上一个问题的示例,该示例为所有不同的特殊字符创建了一个变量,然后我在这里做了我对其他检查所做的事情,将字段输入与特殊字符匹配到变量以查看是否存在是任何,但它没有检测到它们。
这是我的 JavaScript:
function ValidateActInsert() {
var specialChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
这是我试图在上面执行此操作的 HTML 表单:
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
代码本身对我来说很有意义,我想它会起作用,老实说,我不知道为什么它不起作用
解决方案
你抓住了每一个符号。
正如@SterlingArcher 所说,让我们简单地只允许
a-z
小写、
A-Z
大写和或
。0-9
/[^a-zA-Z ]/g
将只允许 az 和 AZ
/[^a-zA-Z0-9 ]/g
将只允许 az、AZ 和 0-9
字母和数字:
function ValidateActInsert() {
var specialChars = /[^a-zA-Z0-9 ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
仅限数字
function ValidateActInsert() {
var specialChars = /[^a-zA-Z ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
我建议使用https://regexr.com/来测试表达式并从一些示例中学习。
推荐阅读
- javascript - 我不确定我是在滥用 SwitchNavigator 还是只是遗漏了一些东西
- thingsboard - 如何对齐标题文本?
- javascript - 如何使用不和谐机器人返回变量
- xamarin - 标签与控件不对齐
- python - 使用 pyinstaller 生成的 EXE 文件在启动时崩溃
- parsing - 如何从 GADT / 存在类型的有效负载中提取有用信息?
- ruby - 从 Capistrano 任务创建 gem
- javascript - 仅使用类将 div 插入现有 div
- php - Laravel - 仅显示今天使用碳创建的帖子
- java - 使用 gradle 和 intellij 为 JavaFX 构建 FatJar,得到 NoClassDefFOundError