使用正则表达式C#验证密码 [英] Validating password using regex c#
问题描述
这必须很简单,我希望它以相同的方式工作,但这并不能帮助我.
This must be simple and I expect it working in the same way but it's not helping me out.
using System;
using System.Text.RegularExpressions;
在某些情况下,我需要密码验证正则表达式
-
I am in a need of password validation regular expression
with certain conditions where -
1)它必须至少包含一个数字
1) It must contain at least a number
2)一个大写字母
3)8个字符长.
public class Program
{
public static bool IsValidPassword(string plainText) {
Regex regex = new Regex(@"^(.{0,7}|[^0-9]*|[^A-Z])$");
Match match = regex.Match(plainText);
return match.Success;
}
public static void Main()
{
Console.WriteLine(IsValidPassword("shing")); //logs 'True' always
}
}
I've taken regex from this source- Password must be 8 characters including 1 uppercase letter, 1 special character, alphanumeric characters
问题是它总是返回"True",而我发送给方法的字符串无效.
Issue is that it returns 'True' always and the string that I am sending to method is not valid.
如果我对正则表达式做错了事,请帮助我.
Help me if I am doing something wrong with the regex.
请在此处使用它- https://dotnetfiddle.net/lEFYGJ
推荐答案
我建议您创建单独的模式来验证密码:
I recommend you create separate patterns to validate the password:
var input = "P@ssw0rd";
var hasNumber = new Regex(@"[0-9]+");
var hasUpperChar = new Regex(@"[A-Z]+");
var hasMinimum8Chars = new Regex(@".{8,}");
var isValidated = hasNumber.IsMatch(input) && hasUpperChar.IsMatch(input) && hasMinimum8Chars.IsMatch(input);
Console.WriteLine(isValidated);
这篇关于使用正则表达式C#验证密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!