please help! I've been at this for hours.
I need a first name regex that accepts letters and the following special characters.
-
, '
, .
and whitespace
However, it must NOT let the name be made up of only special characters or whitespace.
So, in essence it needs to have at least 1 letter, or start with a letter.
What I've got is this;
/^[a-zA-Z](|\s|.|'|-]*$)/i
However, it's allowing any special characters. If someone could help!
CodePudding user response:
/^(?=.*[a-z])[a-z\s.'-] $/i
(?=.*[a-z])
Require at least a ASCII letter. (positive lookahead)
You can either use
(match 1 or more) or *
(match 0 or more).
Note: Because of the flag i
you don't need A-Za-z
. It's case insensitive. So only one of them is necessary. Using both with i-flag is redundant.
Trivia: Escaping .
in character set [...]
is not required but optional possible (\.
).
const regex = /^(?=.*[a-z])[a-z\s.'-] $/i;
console.log(regex.test('Hello World'), 'should be true');
console.log(regex.test('Hello.World'), 'should be true');
console.log(regex.test('Hello-World'), 'should be true');
console.log(regex.test(`'Hello- World.'`), 'should be true');
console.log(regex.test('Hello $ World'), 'should be false');
console.log(regex.test('Hello@World'), 'should be false');
// Min. one A-Z char required.
console.log(regex.test(`'.- `), 'should be false');
You can also test your regex online on e.g. regexr or regex101.
CodePudding user response:
A string made up of all -
, '
, .
, whitespace and letters is
^[-'.\sa-zA-Z] $
A string that has at least one letter in it has an unlimited number of the above sandwiching a single letter:
^[-'.\sa-zA-Z]*[a-zA-Z][-'.\sa-zA-Z]*$
You can denote the letters however you want. a-zA-Z
can be just a placeholder.
CodePudding user response:
Instead of using a single regex, you could also opt to use multiple. In you scenario this would be 2:
- Check if only whitelisted characters are used.
- Check if at least one (ASCII) letter is used.
function validateName(name) {
const whitelist = /^[-'.\sa-z]*$/i;
const letter = /[a-z]/i;
return whitelist.test(name) && letter.test(name);
}
console.log("John Doe", "//=>", validateName("John Doe"));
console.log("John F. Kennedy", "//=>", validateName("John F. Kennedy"));
console.log("Willem-Alexander", "//=>", validateName("Willem-Alexander"));
console.log("Jeanne d'Arc", "//=>", validateName("Jeanne d'Arc"));
console.log("-' .", "//=>", validateName("-' ."));