簡體   English   中英

驗證表單時如何檢查特殊字符

[英]How to check for special characters when validating a form

我正在嘗試將表單驗證添加到我的表單中。 我已經設法做到了字符長度,數字,字母,並且它們都可以正常工作,但是它似乎不適用於特殊字符,例如@&*等。

我試着按照上一個問題的示例進行操作,該示例為所有不同的特殊字符創建了一個變量,然后在此處執行與其他檢查相同的操作,將字段輸入與具有特殊字符的變量匹配,以查看是否存在有,但沒有檢測到它們。

這是我的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所說的那樣,只允許az小寫, AZ大寫和或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 AZ, az 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 AZ, az 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/測試表達式並從一些示例中學習。

使用regex.test(val)

^ [0-9a-zA-Z] * $

^開始

[0-9a-zA-Z]僅允許[]中的字符

$ end *包含的字符數

 function ValidateActInsert() { var regex = /^[0-9a-zA-Z ]*$/; var val = document.getElementsByTagName('input')[0].value; if(!regex.test(val)){ alert("false"); }else{ alert("true"); } return false; } 
 <form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()"> Actor name:<br> <input type = "text" name = "actInsert"> <br> <input type = "submit" value = "Insert"> </form> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM