[英]How to ask for user input with letters (a-z) only without special characters or numbers in C#
[英]How to validate textbox input if its special characters/symbols or letters in c#?
條件是 (a) 檢查文本框是否為 null 或為空。(b) 文本框不應接受符號和字母等無效輸入。 我的程序是一個簡單的 ATM 機
以下是解決驗證問題的提示。 問題是我不知道如何驗證特殊字符和符號我只知道如何驗證文本框是否為空。 如果用戶單擊保存,如果它在文本框中輸入字母或符號,它應該向用戶發送消息。
double userDefinedVariableName;
if (double.TryParse(TextBox.Text, out userDefinedVariableName)) {//code block}
double parsedNumber;
if (double.TryParse(txtNumber.Text, out parsedNumber)) {//code block}
private void btn_save_Click(object sender, EventArgs e)
{
if (withdraw)
{
//balance = balance - double.Parse(txtbox_trans.Text);
//MessageBox.Show("Your balance: " + balance.ToString() + "", "WITHDRAWAL SUCCESSFUL");
withdraw = false;
if (balance > double.Parse(txtbox_trans.Text))
{
if (double.Parse(txtbox_trans.Text) < 500)
{
MessageBox.Show("Minimum withdrawal amount is : 500\nInput a higher amount.", "Amount");
withdraw = true;
}
else
{
balance = balance - double.Parse(txtbox_trans.Text);
MessageBox.Show("Your current balance: " + balance.ToString() + "", "WITHDRAWAL SUCCESSFUL");
btn_cb.Enabled = false;
btn_dp.Enabled = false;
btn_withdraw.Enabled = false;
btn_cancel.Enabled = false;
btn_save.Enabled = false;
btn_new.Enabled = true;
txtbox_trans.Enabled = false;
txtbox_trans.Text = "CLICK NEW TRANSACTION";
}
}
else
{
MessageBox.Show("Your current balance is not enough!\nPlease enter a lower amount.", "Not enough balance");
withdraw = true;
}
}
else if (deposit)
{
deposit = false;
if (100 > double.Parse(txtbox_trans.Text))
{
MessageBox.Show("Minimum deposit amount is : 100\nInput a higher amount.", "Amount");
deposit = true;
}
else if (100000 <= double.Parse(txtbox_trans.Text))
{
MessageBox.Show("Maximum deposit amount is : 100000\nInput a higher amount.", "Amount");
deposit = true;
}
else
{
balance = balance + double.Parse(txtbox_trans.Text);
MessageBox.Show("Your current balance: " + balance.ToString() + "", "DEPOSIT SUCCESSFUL");
deposit = false;
btn_cb.Enabled = false;
btn_dp.Enabled = false;
btn_withdraw.Enabled = false;
btn_cancel.Enabled = false;
btn_save.Enabled = false;
btn_new.Enabled = true;
txtbox_trans.Enabled = false;
txtbox_trans.Text = "CLICK NEW TRANSACTION";
}
}
}
您可以使用正則表達式來檢查它是否是有效輸入。 它看起來像這樣:
Regex pattern = new Regex("^[0-9]+$");
if (pattern.IsMatch(txtbox_trans.Text))
{ // the textbox has valid input, do stuff
int amount = Convert.ToInt32(txtbox_trans.Text);
}
此正則表達式僅匹配從字符串開頭到結尾的數值。 所以如果有任何其他字符,它將不匹配。
您也可以只使用Int32.TryParse
(這可能更容易),如下所示:
int amount = 0;
if (Int32.TryParse(txtbox_trans.Text, out amount))
{
// valid input, do stuff
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.