簡體   English   中英

只接受字母和空格的正則表達式

[英]Regular expression that ONLY accept letters and white spaces

我正在研究 function 驗證用戶輸入的輸入並檢查格式,當我的代碼運行時,如果用戶只輸入字母或數字,則正則表達式有效。 但是如果用戶輸入單詞和字母的組合,output 應該是“格式不正確”時,output 是“格式正確”

function nameValidation(){

    // Grabs name from the input box.
    var name = document.getElementById('name').value;

    var format = /[^0-9]+/g;

    var match = format.test(name);

    if(match){
        alert("correct format");
    } else {
        alert("incorrect format");
    }
}

if user enters "abcdef" output is"correct format" if user enters "123" output is "incorrect format" if user enters "adbda1234" output is "correct format" output should be "incorrect format"

如果你真的只想接受字母和空格,你會想要[a-zA-Z]+\s*

然而,就像評論說的那樣,可能還有其他情況需要考慮,所以一定要看看像regex101.com這樣的網站來處理你的結果。

根據您的問題,您只需要匹配字母和空格。

下面的正則表達式將解決您的問題。

/^[A-Za-z\s]+$/g

上述正則表達式的說明:

1) ^ 檢查字符串是否以字母或空格開頭。

2) $ 檢查字符串是否以字母或空格結尾。

3) + 檢查字符串是否有一個或多個字母或空格。

暫無
暫無

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

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