...

/

Validation of User Input with Regex

Validation of User Input with Regex

Let's apply the rules to individual fields now so they can validate appropriately

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:

Press + to interact
function isValidName(name) {
const nameRegex = /^[a-zA-Z]+$/;
return name.test(nameRegex);
}

​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 ...