I would like to write a regexp to check if the user inserted at least two words separated by at least one empty space:
Example:
var regexp = new RegExp(/^[a-z,',-]+(\s)[a-z,',-]+$/i);
regexp.test("D'avid Camp-Bel"); // true
regexp.test("John ---"); // true // but it should be false!
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Using JavaScript, the full name validation can be easily implemented in the form to check whether the user provides their first name and last name properly. The REGEX (Regular Expression) is the easiest way to validate the Full Name (first name + last name) format in JavaScript.
Does ^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$
work for you?
[a-z]
ensures that a name always starts with a letter, then [-']?[a-z]+
allows for a seperating character as long as it's followed by at least another letter. *
allows for any number of these parts.
The second half, ( [a-z]([-']?[a-z]+)*)
matches a space followed by another name of the same pattern. +
makes sure at least one additional name is present, but allows for more. ({1,2}
could be used if you want to allow only two or three part names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With