我正在尝试将表单验证添加到我的表单中。我已经成功地对字符长度、数字、字母进行了处理,并且所有这些都工作正常,但它似乎不适用于特殊字符,例如 @ & * 等。
我尝试遵循上一个问题中的示例,该示例为所有不同的特殊字符创建了一个变量,然后我在这里执行了我对其他检查所做的操作,将变量的字段输入与特殊字符相匹配看看是否有,但它没有检测到它们。
这是我的 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>
代码本身对我来说很有意义,我想它会起作用,但老实说我不知道为什么它不起作用
最佳答案
你捕捉到了每一个符号。
让我们简单地只允许
a-z
小写,
A-Z
大写和或
0-9
正如 @SterlingArcher 所说。
/[^a-zA-Z ]/g
仅允许 a-z 和 A-Z
/[^a-zA-Z0-9 ]/g
仅允许使用 a-z、A-Z 和 0-9
Letters and Numbers:
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>
Numbers only
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 - 验证表单时如何检查特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55342069/