简体   繁体   中英

How can I validate a password to contain at least one upper-case or lower-case letter?

Criteria

  1. Password length >=8 and <=15
  2. One digit(0-9), One alphabet(AZ or az), One special character (@#$*!)

I tried this

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,15})

but this checks for both one lower case and upper case , but I need either one.

As the saying goes: "I had a problem, so I thought of using a regex. Now I have two problems".

There's nothing wrong with a good ol' method.

public bool IsPasswordValid(string password)
{
    return password.Length >= 8 &&
           password.Length <= 15 &&
           password.Any(char.IsDigit) &&
           password.Any(char.IsLetter) &&
           (password.Any(char.IsSymbol) || password.Any(char.IsPunctuation)) ;
}

根据 ,这是一个RegEx,其中包括所有允许的特殊符号:

((?=.*\d)(?=.*[a-zA-Z])(?=.*[@!-'()\+--\/:\?\[-`{}~]).{8,15})

只需删除AZ匹配组并使用RegexOptions.IgnoreCase声明正则表达式即可忽略大小写(即,所提供的字母是大写,小写还是两者都不重要; az组仍将匹配它们):

new Regex(@"((?=.*\d)(?=.*[a-z])(?=.*[@#$%]).{8,15})", RegexOptions.IgnoreCase)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM