On the system I am working with, we have a Password class that validates by throwing exceptions under the following conditions:
public Password(string password)
: base(password)
{
// Must contain digit, special character, or uppercase character
var charArray = password.ToCharArray();
var hasDigit = charArray.Select(c => char.IsDigit(c)).Any();
var hasSpecialCharacter = charArray.Select(c => char.IsSymbol(c)).Any();
var hasUpperCase = charArray.Select(c => char.IsUpper(c)).Any();
if (!hasDigit && !hasSpecialCharacter && !hasUpperCase)
{
throw new ArgumentOutOfRangeException
("Must contain at least one digit, symbol, or upper-case letter.");
}
}
If I was going to write this same check for hasDigit, hasSpecialCharater, and hasUpperCase in JavaScript, what would it look like?
JavaScript does not have these same character prototypes, so I’ve got to use regular expressions, no?
The three conditions can be combined together with:
where
\d→ 1 digit (0-9),\W→ 1 non-word character (anything except 0-9, a-z, A-Z and _) This matches more character than C#’sIsSymbol, in case the password supports characters outside of ASCII,[A-Z]→ 1 uppercase characterbut the only characters which doesn’t match
\d|\W|[A-Z]areatoz, which we may as well simply write