我正在创建一个窗口表单,只有在符合某些条件时才允许输入密码。我接近完成但是我有点卡在一个元素。 "密码的第一个和最后一个字符必须是数字"。
查看我当前的代码我将如何解决这个问题,因为我有ZERO的想法。所以宝贝的步骤和耐心将不胜感激。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace password_test
{
public partial class Form1 : Form
{
bool Finished = false;
private bool TestPassword(string passwordText, int minimumLength = 5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
{
int letters = 0;
int digits = 0;
int minLetters = 0;
if (passwordText.Length < minimumLength)
{
MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
return false;
}
if (passwordText.Length > maximumLength)
{
MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
return false;
}
foreach (var ch in passwordText)
{
if (char.IsLetter(ch)) letters++;
if (char.IsDigit(ch)) digits++;
if (ch > 96 && ch < 123)
{
minLetters++;
}
}
if (digits < minimumNumbers)
{
MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
return false;
}
if (minLetters < minimumLetters)
{
MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
return false;
}
Finished = true;
return true;
}
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void butConfirm_Click(object sender, EventArgs e)
{
if (txtPassword.Text == txtRetypePassword.Text)
{
bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);
if (Finished == true)
{
MessageBox.Show("Password Accepted");
Application.Exit();
//this.Hide();
//Form2 f2 = new Form2();
//f2.ShowDialog();
}
}
else
{
MessageBox.Show("Please ensure the passwords you have typed match");
return;
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
return;
}
}
private void txtRetypePassword_TextChanged(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:0)
在Finished = true;
之前,您只需进行检查即可:
if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
MessageBox.Show("The first and last characters of the password have to be numbers");
return false;
}
Finished = true;
您还应该在方法中强制执行最小长度。
答案 1 :(得分:0)
或者您可以使用正则表达式Test Pattern
// ^\d = start with digit
// \d$ end with digit
// .{3,10} including start and ending, min 5 max 12
if (!Regex.IsMatch(str, @"\d.{3,10}\d$")
{
// Invalid
}
使用\ D反转。