繁体   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