C# 验证文本框是否应包含一个数字和一个特殊字符
这是我的C#代码:C# 验证文本框是否应包含一个数字和一个特殊字符,c#,winforms,C#,Winforms,这是我的C#代码: 如何在单击登录按钮时验证密码应至少包含一个数字和一个特殊字符 对不起,我还不能评论,但是你不是已经在特殊字符中使用正则表达式了吗 if (Regex.IsMatch(txtPassword.Text, @"(!|@|#)")) { MessageBox.Show("Password Must Contain at least a special character"); } 如果我没弄错你的问题,你也可以用数字或字母来回答 看看这个已回答的问题,它可以帮助您
如何在单击登录按钮时验证密码应至少包含一个数字和一个特殊字符 对不起,我还不能评论,但是你不是已经在特殊字符中使用正则表达式了吗
if (Regex.IsMatch(txtPassword.Text, @"(!|@|#)"))
{
MessageBox.Show("Password Must Contain at least a special character");
}
如果我没弄错你的问题,你也可以用数字或字母来回答
看看这个已回答的问题,它可以帮助您:
更新
这是因为你不使用->!在Regex.IsMatch之前,因此MessageBox仅在用户输入特殊字符时出现,而在用户不输入字符时不会出现
试试这个:
if (!Regex.IsMatch(txtPassword.Text, @"(!|@|#)"))
{
MessageBox.Show("Password Must Contain at least a special character");
}
您可以通过测试从用户输入检索的字符串来实现这一点。为此,最好使用
regex
Regex regexPassword = new Regex( @"
^ // From the start of the string
[a-zA-Z0-9!@#]+ // The string should contain some of these characters, like letters including digits and special chars
(<=[!@#]) // one of these should be a special character
(<=[0-9]) // one of these should be a number
$ // end of string
" , RegexOptions.IgnorePatternWhitespace ) ;
试试下面的代码
if (!Regex.IsMatch(txtPassword.Text, @"(!|@|#)") || !txtPassword.Text.Any(char.IsDigit))
{
Console.WriteLine("Password Must Contain at least a special character and digit");
}
else
{
// DO YOUR STUFF
}
即使特殊字符没有输入到另一个窗体并且没有显示消息框,正则表达式代码也不起作用。我不知道这是否是问题所在,但您是否考虑过在密码错误时剪切程序,可能是使用此.close()或return?像这样的?直到现在,您的else路径每次都被执行,它是否因此改变了形式?
if(regexPassword.IsMatch(yourPasswordString))
{
//Do what you want
}
if (!Regex.IsMatch(txtPassword.Text, @"(!|@|#)") || !txtPassword.Text.Any(char.IsDigit))
{
Console.WriteLine("Password Must Contain at least a special character and digit");
}
else
{
// DO YOUR STUFF
}