Kaleb Meeks
Kaleb Meeks

Reputation: 111

Javascript Fullname Regex Issue

I have been using a regex code for fullnames in JavaScript and the pattern looks like this : /(\w)\s(\w)/ . The problem is that this pattern accepts numbers which I don't won't in the users fullname. So,I need a pattern that accepts a space after the first name and accepts a second name after the space and has a limit of 30 characters but does not accept numbers. I don't know how to create a regex pattern so any help is appreciated.

This is what the code looks like now:

    if(name.match(/(\w)\s(\w)/)){
        flagOne = true;
    }

Upvotes: 1

Views: 549

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16069

You can use the following pattern to match only alphabetical characters (be aware, that you are now not allowing special characters like çöäüèéà or punctuation characters like ' or -):

/^([A-Za-z]+?)\s([A-Za-z]+?)$/

The length of the full string cannot be measured in this form, but can be easily read out with JavaScript:

name.length;

Here is an example in JavaScript:

var name = "Test Name";
if(name.match(/^([A-Za-z]+?)\s([A-Za-z]+?)$/) && name.length <= 30) {
    console.log("name is valid.");
}

Like @gaetanoM pointet out in the comments, you could also use a more sophisticated regular expression like it is described in this answer.

Upvotes: 1

Related Questions