Validating password in JavaScript; RegEx

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?

Upvotes: 1

Views: 518

Answers (3)

kennytm
kennytm

Reputation: 523284

The three conditions can be combined together with:

if (/\d|\W|[A-Z]/.test(theString)) {
 ...

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#'s IsSymbol, in case the password supports characters outside of ASCII,
  • [A-Z] → 1 uppercase character

but the only characters which doesn't match \d|\W|[A-Z] are a to z, which we may as well simply write

if (/[^a-z]/.test(theString)) {

Upvotes: 1

cdhowie
cdhowie

Reputation: 169008

You should be able to combine all of the tests into one JS regex:

if (!passwordString.match(/[^a-z ]/)) {
    alert('Invalid password.');
    return false;
}

Upvotes: 0

MartinodF
MartinodF

Reputation: 8254

hasDigit:

/\d/.test(password);

hasUpperCase:

/[A-Z]/.test(password);

hasSpecialCharacter:

/[^a-zA-Z0-9]/.test(password);

edit .test is much better than .match

Upvotes: 1

Related Questions