使用 JavaScript 验证表单时检查特殊字符 (, ; .)

Check for special characters (, ; .) while validating a form with JavaScript

我试图在我的(工作)验证脚本中插入这段代码(我在网站上找到的):

if (register.username.match(/\W/)) {
    alert('You have special characters on username field.');
    return false;
}

它什么也没做,而且还阻止了整个脚本的工作。

这是 html 形式(不是全部):

<form name="register" method="POST" action="registar.php" onsubmit="return validateForm();">
    <ul class="left-form">
        <h2>Nova conta:</h2>
        <li>
            <input type="text" name="username" placeholder="Username" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="text" name="email" placeholder="Email" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="password" name="pass" placeholder="Password" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="password" name="pass_confirm" placeholder="Confirmar a password" required/>
            <div class="clear"> </div>
        </li>
        <input type="submit" value="Registar">
        <div class="clear"> </div>
    </ul>
</form>

这是我的 Javscript 代码(没有检查特殊字符):

function validateForm() {
    if (register.username.value.length <= 2) {
        alert("O username escolhido é demasiado curto.");
        return false;
    }
    if (register.username.value.length > 20) {
        alert("O username escolhido é demasiado longo.");
        return false;
    }
    var x = register.email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("O email inserido parece ser inválido.");
        return false;
    }
    if (register.username.value == register.pass.value) {
        alert("Por questões de segurança, pedimos que use uma password diferente do seu nome de utilizador.");
        return false;
    }
    if ((register.pass.value.length < 6) || (register.pass.value.length > 20)) {
        alert("Certifique-se que a sua password tem entre 6 e 20 letras.");
        return false;
    }
    if (register.pass.value != register.pass_confirm.value) {
        alert("As passwords não condizem.");
        return false;
    }
    return true;
}

忽略警报,因为它们只是显示消息。

有人可以写一段代码来检查特殊字符(!、.+ * 等),或者告诉我我使用的代码有什么问题吗?

您可能应该将代码更改为:

if (register.username.value.match(/\W/)) {
   alert('You have special characters on username field.');
   return false;
}

有什么区别?好吧,如果你已经意识到我在中间添加了 .value。因为 register.username 将引用用户名输入元素并且它没有 match 方法。我们需要检查其中输入的文本。通过检查 input element reference, you can realize we use it's value property which returns the text entered. So register.username.value is the text entered by the user and since it's a string we can use .match method 就可以了。

您现在可以将任何正则表达式传递给满足您需要的匹配方法。还要检查 the guide on regex

同时始终检查开发人员控制台中显示的错误。