[英]How to limit the amount of characters allowed in a databound WinForms TextBox
[英]WinForms: How to check for minimum amount of characters in textbox in C#?
我試圖確保用戶在我的程序中使用至少 6 個字符作為密碼。
我知道如何使用MaxLength
設置最大尺寸,但我如何為最小長度做到這一點?
if (passwordTextBox.Text.Length < 6)
{
MessageBox.Show("Passwords must be at least 6 characters long.");
return /*false*/;
}
// Do some stuff...
return /*true*/;
如果您打算擁有多個用戶界面,用戶可以在其中輸入密碼(網絡、移動設備、Windows 客戶端等)或提供用於執行相同操作的服務(網絡、wcf 等),那么我認為您最好的選擇是在所有這些平台的最常見級別捕獲此類錯誤。
我們通常在數據庫中實現這樣的業務規則(通過存儲過程),以便我們有一個眾所周知的位置來檢查和更改這些規則。
如果您使用的數據庫不支持存儲過程,那么您可以在“業務層”或負責為您的應用程序執行業務邏輯的一組代碼中實現此功能。
使用密碼文本框上的驗證方法來強制長度。
if (TextBox1.Text.Length < 6)
{
MessageBox.Show("password too short");
TextBox1.Focus();
}
盡管competent_tech 為您提供了我推薦的方法,但一個原始的解決方案如下:
在您的表單上放置一個標簽並為其指定一個 ErrorText。
為您的文本框 KeyDown 事件使用以下代碼:
protected override void OnLoad(object sender, EventArgs e)
{
base.OnLoad(sender, e);
txtPassword.KeyDown += OnPasswordKeydown;
}
protected void OnPasswordKeydown(object sender, KeyEventArgs e)
{
bool isValid = txtPassword.Text.Length < 6;
ErrorText.Visible = isValid;
AcceptButton.Visible = isValid;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.