![](/img/trans.png)
[英]Regular Expression: Letters, numbers, spaces, hyphens, periods, and underscores only and must begin with a letter
[英]javascript regex to allow letters, numbers, periods, hyphens, underscores, and spaces
我正在嘗試將表單數據(用戶名)附加到URL。 在網站上,用戶名可以包含字母,數字,空格,連字符,下划線和句點。
我正在嘗試創建一個JavaScript正則表達式,以允許這些字符,但僅允許那些字符。
到目前為止,我所允許的例如:
用戶名
但這也將允許用戶名和
我搜索了許多stackover流帖子,但尚未解決。 非常感謝您的建議。 這是我所擁有的..
<script>
function process() {
var regexp1=new RegExp("[^[0-9A-Za-z_.-]+$]");
var url = "http://www.website.com/page.php?data=" + document.getElementById("url").value;
if (regexp1.test(document.getElementById("url").value)) {
alert("Only numbers, letters, hypens, periods, spaces and underscores are allowed");
return false;
}
location.href = url;
return false;
}
</script>
<form onSubmit="return process();">
<br>
<input type="text" size="10" maxlength="30" name="url" id="url">
<input type="submit" value="go">
</form>
至於需要用^
和$
錨定的正則表達式,使其表示“整件事情”並避免部分算術,並且您的空間也位於字符類之外,應位於 。 此外,即使在字符類中,也可以使用\\w+
獲得“字母/數字/下划線”。 最后,我們可以使用i
標志不用擔心大寫字母:
/^[\\w\\s.-]+$/i
您的正則表達式應為:
/^[ A-Za-z0-9_-.\s]*$/i
說明:
^ : Begging of string
A-Z : Uppercase Characters
a-z : Lowercase Characters
0-9 : Numbers
_-. : Special Characters you requested
\s : Spaces
* : Allow repeat
$ : End of string
/i : Case insensitive
您可以用\\w
替換A-Za-z0-9_
而您的If步調應該檢查逆:
if(!regexp1.test...
在功能的最后,最好將其制成
return true;
我建議您檢查JQuery以獲得更高級,更簡單的Javascript代碼
希望這個幫助
您的if語句被顛倒了。 您應該檢查正則表達式何時不匹配:
!regexp1.test(document.getElementById("url").value)
我也相信原始的正則表達式是錯誤的/不正確的,請嘗試如下所示:
function process() { var regexp1=new RegExp("^[0-9A-Za-z_.-]+$"); var url = "http://www.website.com/page.php?data=" + document.getElementById("url").value; if (!regexp1.test(document.getElementById("url").value)) { console.log("Only numbers, letters, hypens, periods, spaces and underscores are allowed"); } else { console.log("Passed validation."); } }
<input type="text" size="10" maxlength="30" name="url" id="url"> <input type="button" onclick="process()">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.