简体   繁体   English

只接受字母和空格的正则表达式

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

I'm working on a function that validates user entered input and it checks the format, when my code runs, if the user only enters letters or numbers the regular expression works.我正在研究 function 验证用户输入的输入并检查格式,当我的代码运行时,如果用户只输入字母或数字,则正则表达式有效。 But if the user enters a combination of words and letters, the output is "correct format" when the output should be "incorrect format"但是如果用户输入单词和字母的组合,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" 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"

If you truly want to only accept letters and white space, you'll want [a-zA-Z]+\s*如果你真的只想接受字母和空格,你会想要[a-zA-Z]+\s*

However, like the comments say, there are likely other cases to account for, so definitely look into a site like regex101.com to play around with your results.然而,就像评论说的那样,可能还有其他情况需要考虑,所以一定要看看像regex101.com这样的网站来处理你的结果。

As per your question you only need to match letters and spaces.根据您的问题,您只需要匹配字母和空格。

Below regular expression will solve your question.下面的正则表达式将解决您的问题。

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

Description of above reg exp:上述正则表达式的说明:

1) ^ checks if string starts with letter or space. 1) ^ 检查字符串是否以字母或空格开头。

2) $ checks if string ends with letter or space. 2) $ 检查字符串是否以字母或空格结尾。

3) + checks if string has one or more letter or space. 3) + 检查字符串是否有一个或多个字母或空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM