检查文本框是否包含数字&其他无效字符

时间:2018-03-30 06:24:53

标签: c#

如何检查文本框是否包含用户输入的字符,我不希望程序接受?数字和其他种类如!@#$ []等。当用户点击按钮时,如果存在无效字符,则会弹出错误消息。

private void btnAddSave_Click(object sender, EventArgs e)
{
    if (txtAddEmployerName.Text.Contains  //INVALID CHARACTERS GO HERE)
    {
        MessageBox.Show("You may only enter letters", "Error");
        return;
    }
}

2 个答案:

答案 0 :(得分:2)

这可以使用正则表达式轻松完成。这将验证用户输入以仅检查字母。

private void btnAddSave_Click(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(txtAddEmployerName.Text, "^[a-zA-Z ]*$"))
    {
        MessageBox.Show("You may only enter letters", "Error");
        return;
    }
}

答案 1 :(得分:0)

你可以尝试 Linq 这是非常直接的:如果txtAddEmployerName.Text包含Any字符,而不是 space 字母显示错误:

 private void btnAddSave_Click(object sender, EventArgs e) {
   // char.IsLetter - any unicode letter, not necessary English ones 
   // e.g. Russian (Cyrillic) are included as well: Это тоже буквы
   // In case you want a..z A..Z only
   //   c => c == '' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
   if (txtAddEmployerName.Text.Any(c => !(c == ' ' || char.IsLetter(c)))) {
     // Let's highlight (i.e. put keyboard focus) on the problem control
     if (txtAddEmployerName.CanFocus)
       txtAddEmployerName.Focus();

     MessageBox.Show("Letters only, please.", "Error");

     return; // seems redundant unless you have more code after the if 
   } 
 }