I am having problems creating a regex validator that checks to make sure the input has uppercase or lowercase alphabetical characters, spaces, periods, underscores, and dashes only. Couldn’t find this example online via searches. For example:
These are ok:
Dr. Marshall
sam smith
.george con-stanza .great
peter.
josh_stinson
smith _.gorne
Anything containing other characters is not okay. That is numbers, or any other symbols.
The regex you’re looking for is
^[A-Za-z.\s_-]+$^asserts that the regular expression must match at the beginning of the subject[]is a character class – any character that matches inside this expression is allowedA-Zallows a range of uppercase charactersa-zallows a range of lowercase characters.matches a periodrather than a range of characters
\smatches whitespace (spaces and tabs)_matches an underscore-matches a dash (hyphen); we have it as the last character in the character class so it doesn’t get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that’s less clear+asserts that the preceding expression (in our case, the character class) must match one or more times$Finally, this asserts that we’re now at the end of the subjectWhen you’re testing regular expressions, you’ll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.