mrblah
mrblah

Reputation: 103517

Regex for alphanumeric password, with at least 1 number and character

Need help with a regex for alphanumeric password, with at least 1 number and character, and the length must be between 8-20 characters.

I have this but doesn't seem to be working (it doesn't have length requirements either):

^[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*$

Upvotes: 3

Views: 15062

Answers (6)

Raj kumar pandey
Raj kumar pandey

Reputation: 1

This code is for javascript

// *********** ALPHA-Numeric check ***************************
function checkAlphaNumeric(val)
{
    var mystring=new String(val)

    if(mystring.search(/[0-9]+/)==-1) // Check at-leat one number
    {
        return false;
    }
    if(mystring.search(/[A-Z]+/)==-1 && mystring.search(/[a-z]+/)==-1) // Check at-leat one character
    {
        return false;
    }
}

Upvotes: 0

S Pangborn
S Pangborn

Reputation: 12739

Why not just use a handful of simple functions to check?

checkPasswordLength( String password);
checkPasswordNumber( String password);

Maybe a few more to check for occurrences of the same character repeatedly and consecutively.

Upvotes: 3

John Fisher
John Fisher

Reputation: 22719

Something like this will be closer to your needs. (I didn't test it, though.)

Regex test = new Regex("^(?:(?<ch>[A-Za-z])|(?<num>[9-0])){8,20}$");
Match m = test.Match(input);
if (m.Success && m.Groups["ch"].Captures.Count > 1 && m.Groups["num"].Captures.Count > 1)
{
  // It's a good password.
}

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

If you take a look at this MSDN link, it gives an example of a password validation RegEx expression, and (more specifically) how to use it in ASP.NET.

For what you're looking to accomplish, this should work:

    (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,20})$

This requires at least one digit, at least one alphabetic character, no special characters, and from 8-20 characters in length.

Upvotes: 10

Sanjay Sheth
Sanjay Sheth

Reputation: 1619

Wouldn't it be better to do this validation with some simple string functions instead of trying to shoehorn a difficult to validate regex into doing this?

Upvotes: 0

cwap
cwap

Reputation: 11287

^(?=.{8,20}$)(?=.*[0-9])(?=.*[a-zA-Z]).*

? :)

Upvotes: 1

Related Questions