首页 > 解决方案 > 验证表单时如何检查特殊字符

问题描述

我正在尝试将表单验证添加到我的表单中。我已经设法对字符长度、数字、字母进行了处理,并且它们都可以正常工作,但它似乎不适用于特殊字符,例如 @ & * 等。

我已经尝试按照上一个问题的示例,该示例为所有不同的特殊字符创建了一个变量,然后我在这里做了我对其他检查所做的事情,将字段输入与特殊字符匹配到变量以查看是否存在是任何,但它没有检测到它们。

这是我的 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>

代码本身对我来说很有意义,我想它会起作用,老实说,我不知道为什么它不起作用

标签: javascript

解决方案


你抓住了每一个符号。

正如@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/来测试表达式并从一些示例中学习。


推荐阅读