C# .NET - Regular Expression for Password to allow alphanumeric characters

Asked By abinav shankar on 15-Jan-12 11:08 AM

Hi

I want a regularfield expression for password which allows alphanumeric characters with one special characters

thanks

[)ia6l0 iii replied to abinav shankar on 15-Jan-12 11:27 AM
You might have to tweak this a little. "-&_ " takes care of special character.
^(?:(?>[a-zA-Z0-9]+)(?:[-&_ ](?![-&_ ]|$))?)+$

Or, you can use the following one to check for alphanumeric characters and then add another one for "one" special character.
^([a-zA-Z0-9])$
D Company replied to abinav shankar on 15-Jan-12 11:42 AM
Hello Abinav

try this

^(?:(?>[0-9A-Za-z]+)(?:[-&_ ](?![-&_ ]|$))?)+$

or

^[0-9a-zA-Z'.][\^$.|?*+(){1,1}$"))

{1,1 } is for allowing only one special charecter

Regards
D
kalpana aparnathi replied to abinav shankar on 15-Jan-12 12:08 PM
hi,

Pass it through multiple regexes if you can. It'll be a lot cleaner than those look-ahead monstrosities :-)

^[a-zA-Z0-9]{6,10}$
[a-zA-Z]
[0-9]


Though some might consider it clever, it's not necessary to do everything with a single regex (or even with any regex, sometimes - just witness the people who want a regex to detect numbers between 75 and 4093).

Would you rather see some nice clean code like:


if not checkRegex(str,"^[0-9]+$")
    return false
val = string_to_int(str);
return (val >= 75) and (val <= 4093)


or something like:


return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$")
kalpana aparnathi replied to abinav shankar on 15-Jan-12 12:10 PM
Try this:

Regex :
      ^(?=.*\d)\w{6,30}$

Riley K replied to abinav shankar on 15-Jan-12 09:02 PM


The below one 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. 

Regards
smr replied to abinav shankar on 15-Jan-12 11:16 PM
hi

I would guess that by letter you mean 'a-z' or 'A-Z', by digit you mean '0-9' and by symbol you mean any other printable ASCII character. If so, try this:

static bool IsLetter(char c)
{
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
  
static bool IsDigit(char c)
{
  return c >= '0' && c <= '9';
}
  
static bool IsSymbol(char c)
{
  return c > 32 && c < 127 && !IsDigit(c) && !IsLetter(c);
}
  
static bool IsValidPassword(string password)
{
  return
     password.Any(c => IsLetter(c)) &&
     password.Any(c => IsDigit(c)) &&
     password.Any(c => IsSymbol(c));
}

follow
http://stackoverflow.com/questions/3373583/check-password-contains-alphanumeric-and-special-character