简体   繁体   English

如何验证密码至少包含一个大写或小写字母?

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

Criteria 标准

  1. Password length >=8 and <=15 密码长度> = 8和<= 15
  2. One digit(0-9), One alphabet(AZ or az), One special character (@#$*!) 一位(0-9),一位字母(AZ或az),一位特殊字符(@#$ *!)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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