Validation of User Input with Regex
Explore how to use regular expressions to validate different user inputs such as names, usernames, passwords, birthdays, and phone numbers. Understand regex patterns and practical validation strategies to build responsive, user-friendly auto-validating forms.
We'll cover the following...
Name #
Original rule: Non-empty string of alpha characters
Without regex, the non-empty part can be enforced by .length and the alpha part can be enforced by checking if the character is within the list ['a', 'b', ..., 'z', 'A', 'B', ..., 'Z']. With regex, the alpha part is matched by /[a-zA-Z]/ (don’t forget capital letters!), and the nonempty part through the symbol + (which means one or more). So that gives us:
The ^ means “start” and $ means “end.” Since test checks that our regex has a match in any part of the string and we want to validate on the entirety of the string, we need to add those. Otherwise, inputs like @#$@#$#@ username would pass.
Username #
Original rule: Non-empty string of number, letter, period, or ...