簡體   English   中英

在輸入中只允許使用字母,數字和連字符?

[英]Allow only letters, numbers, and hyphen in input?

我想在輸入中只接受字母,數字和連字符(破折號)。 在PHP中,我這樣做:

if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}

如何在vanilla javascript中實現同樣的功能? 如果它不可能在純JavaScript中,我怎么能在jquery中做到這一點? 謝謝

改編自Sylvain的答案: jQuery只允許數字,字母和連字符

注意:jQuery幾乎是vanilla js的包裝器,可以使很多常見的語句如Document.querySelectorAll()更短,通常可以安全地假設jQuery可以直接轉換為vanilla js(我想不出任何例子關閉我的頭頂jQuery功能不同)。

你可以做的是在表單中選擇所有的輸入(或任何你想),然后對一個正則表達式測試他們的價值觀(維爾托德使用的選擇所需的字符的逆所以,這將是一個正則表達式true ,如果有一個無效字符)如果它有任何禁止字符,則阻止表單提交並做一些其他事情要求用戶解決問題。

 document.getElementById("formWhitelistedChars").addEventListener("submit", function(e) { // Get all inputs in the form we specifically are looking at, this selector can be // changed if this is supposed to be applied to specific inputs var inputs = document.querySelectorAll('#formWhitelistedChars input'); var forbiddenChars = /[^az\\d\\-]/ig; // check all the inputs we selected for(var input of inputs) { // Just in case the selector decides to do something weird if(!input) continue; // Check that there aren't any forbidden chars if(forbiddenChars.test(input.value)) { // This line is just to do something on a failure for Stackoverflow // I suggest removing this and doing something different in application console.log('input ' + input.name + ' has forbidden chars.'); // Do stuff here // Prevent submit even propagation (don't submit) e.preventDefault(); return false; } } }); 
 <form id="formWhitelistedChars"> <input name="1" /> <input name="2" /> <button type="submit">Submit</button> </form> 

編輯:用評論中提到的@ibrahimmahrir替換0-9\\d

EDIT2:將輸入偵聽器更改為表單提交

您可以使用/{criteria}/{flags}啟動新的正則表達式。 你的正則表達式會轉換成這樣的東西:

/^[aA-zZ0-9-]+$/g.test(/* value to test here*/)

暫無
暫無

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

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