简体   繁体   中英

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. But if the user enters a combination of words and letters, the output is "correct format" when the output should be "incorrect format"

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 you truly want to only accept letters and white space, you'll want [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.

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.

2) $ checks if string ends with letter or space.

3) + checks if string has one or more letter or space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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