gpt4 book ai didi

c# - 确保文本框的第一个和最后一个字符是数字c#

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:18 27 4
gpt4 key购买 nike

我目前正在创建一个 Windows 窗体,该窗体必须仅在符合特定条件时才允许密码通过。我快要完成了,但是我有点被一个元素困住了。 “密码的第一个和最后一个字符必须是数字”。

查看我当前的代码,我将如何解决这个问题,因为我的想法为零。所以婴儿的步骤和耐心将不胜感激。

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)
{

}




}
}

最佳答案

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;

您还应该在您的方法中强制执行最小长度。

关于c# - 确保文本框的第一个和最后一个字符是数字c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44992204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com