Raffy Eid
Raffy Eid

Reputation: 21

Name Validation Using Regular Expressions

I'm using a regular expression in my code, to validate the name and send the form, I just need some help by using it.

The Name should start by a capital letter and could be from 2-3 words, and could be separated by an apostrophe, space or a dash such as :

Victor Hugo

Jeanne D'arc

Jean-Marc Ayrault

I tried starting it by a capital, using /^[A-z][a-z]/ But i don't know how to continue it to validate spaces and dashes and apostrophes.

/^[A-z][a-z]/

I don't know how to continue it, thank you for your help.

Upvotes: 1

Views: 144

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30725

You could try the code below:

I'd suggest playing about with https://regexr.com/ for this purpose, it's very handy!

I've added a isValidNameStrict which only accepts a limited number of characters in the name.

Modify the [a-z'] group as you see fit to add extra characters.

function isValidNameStrict(name) {
    let regEx = /^([A-Z][a-z']*[\-\s]?){2,}$/;
    return regEx.test(name);
}

function isValidName(name) {
    let regEx = /^(?:[A-Z][^\s]*\s?){2}$/;
    return regEx.test(name);
}

function testName(name) {
    console.log(`'${name}' is ${isValidNameStrict(name) ? "valid": "not valid"}`);
}

testName("Victor Hugo");
testName("Jeanne D'arc");
testName("Jean-Marc Ayrault");
testName("The Rock");
testName("Victor hugo");
testName("");
testName("Ozymandias");

Upvotes: 0

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex,

\b[A-Z][a-z]*(?:'[a-z]+)?(?:[ -][A-Z][a-z]*(?:'[a-z]+)?)*\b

Explanation:

  • \b[A-Z][a-z]* - Starts matching a word boundary and uppercase letter followed by zero or more lowercase letters
  • (?:'[a-z]+)? - Optionally followed by ' and some lowercase letters. If you want to repeat this more than once, change ? to * like if you really want to support names like D'arcd'arc which I doubt if you wanted which is why I kept it with ?
  • (?:[ -] - Starts another non-grouping pattern and starts matching either with a space or hyphen
  • [A-Z][a-z]*(?:'[a-z]+)?)* - Further matches the same structure as in start of regex and zero or more times.
  • \b - Stops after seeing a word boundary

Demo

Upvotes: 2

Related Questions