C# C语言的输入验证和异常#

C# C语言的输入验证和异常#,c#,winforms,validation,exception-handling,C#,Winforms,Validation,Exception Handling,我正在尝试验证输入并处理此程序中的异常。验证以下内容:txtNAME中的字符串不应保留为空,txtNAME中的电话号码应至少为10位数字,并且TXTMail应采用带有“@”和“.”的电子邮件格式。如何验证这些输入,并在输入错误的输入时处理异常 public partial class Form1 : Form { static int maxCount = 10; int[] employeeID = new int[maxCount]; string[] employ

我正在尝试验证输入并处理此程序中的异常。验证以下内容:txtNAME中的字符串不应保留为空,txtNAME中的电话号码应至少为10位数字,并且TXTMail应采用带有“@”和“.”的电子邮件格式。如何验证这些输入,并在输入错误的输入时处理异常

public partial class Form1 : Form
{
    static int maxCount = 10;

    int[] employeeID = new int[maxCount];
    string[] employeeName = new string[maxCount];
    string[] jobTitle = new string[maxCount];
    string[] address = new string[maxCount];
    int[] telephoneNumber = new int[maxCount];
    string[] email = new string[maxCount];

    int addCount = 0;

    string fn = "employees.xml";

    int currentRec;

    private void btnADD_Click(object sender, EventArgs e)
    {
        employeeID[addCount] = Convert.ToInt32(txtEI.Text);
        employeeName[addCount] = txtNAME.Text;
        jobTitle[addCount] = txtJOB.Text;
        address[addCount] = txtADDRESS.Text;
        telephoneNumber[addCount] = Convert.ToInt32(txtTELEPHONE.Text);
        email[addCount] = txtEMAIL.Text;
        addCount++;
    }

    private void btnSAVE_Click(object sender, EventArgs e)
    {
      XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
      w.Formatting = Formatting.Indented;
      w.WriteStartDocument();
      w.WriteStartElement("employees");
      for (int i = 0; i < addCount; i++)
      {
          w.WriteStartElement("employees");

          w.WriteElementString("employeeID", employeeID[i].ToString());
          w.WriteElementString("employeeName", employeeName[i]);
          w.WriteElementString("jobTitle", jobTitle[i]);
          w.WriteElementString("address", address[i]);
          w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
          w.WriteElementString("email", email[i]);
          w.WriteEndElement();
      } w.WriteEndElement();
      w.WriteEndDocument();
      w.Close();
      Application.Exit();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists(fn))
        {
            XmlTextReader r = new XmlTextReader(fn);
            r.WhitespaceHandling = WhitespaceHandling.None;
            while (r.Name != "employees")
                r.Read();
            while (r.Name == "employees")
            {
                r.ReadStartElement("employees");
                employeeID[addCount] = Convert.ToInt32(r.ReadElementString("employeeID"));
                employeeName[addCount] = r.ReadElementString("employeeName");
                jobTitle[addCount] = r.ReadElementString("jobTitle");
                address[addCount] = r.ReadElementString("address");
                telephoneNumber[addCount] = Convert.ToInt32(r.ReadElementString("telephoneNumber"));
                email[addCount] = r.ReadElementString("email");
                r.ReadEndElement();
                addCount++;

            } r.Close();
            DisplayRec();
        }
    }

    private void DisplayRec()
    {
        txtEI.Text = employeeID[currentRec].ToString();
        txtNAME.Text = employeeName[currentRec];
        txtJOB.Text = jobTitle[currentRec];
        txtADDRESS.Text = address[currentRec];
        txtTELEPHONE.Text = telephoneNumber[currentRec].ToString();
        txtEMAIL.Text = email[currentRec];
        lblRECORD.Text = (currentRec + 1).ToString() + "/" + addCount.ToString();

    }

    private void btnBACK_Click(object sender, EventArgs e)
    {
        if (currentRec > 0)
            currentRec--;
        DisplayRec();
    }

    private void btnNEXT_Click(object sender, EventArgs e)
    {
        if (currentRec < addCount - 1)
            currentRec++;
        DisplayRec();
    }

    private void btnCLEAR_Click(object sender, EventArgs e)
    {
        txtEI.Clear();
        txtNAME.Clear();
        txtJOB.Clear();
        txtADDRESS.Clear();
        txtTELEPHONE.Clear();
        txtEMAIL.Clear();

    }
}
公共部分类表单1:表单
{
静态int maxCount=10;
int[]employeeID=新int[maxCount];
string[]employeeName=新字符串[maxCount];
string[]jobTitle=新字符串[maxCount];
字符串[]地址=新字符串[maxCount];
int[]电话号码=新的int[maxCount];
字符串[]电子邮件=新字符串[maxCount];
int addCount=0;
字符串fn=“employees.xml”;
int currentRec;
私有void btnADD_单击(对象发送者,事件参数e)
{
employeeID[addCount]=Convert.ToInt32(txtEI.Text);
employeeName[addCount]=txtNAME.Text;
jobTitle[addCount]=txtJOB.Text;
地址[addCount]=txtADDRESS.Text;
电话号码[addCount]=转换为32(txtTELEPHONE.Text);
email[addCount]=txtEMAIL.Text;
addCount++;
}
私有void btnSAVE\u单击(对象发送方,事件参数e)
{
XmlTextWriter w=新的XmlTextWriter(fn,Encoding.UTF8);
w、 格式化=格式化。缩进;
w、 WriteStartDocument();
w、 书面启动(“员工”);
for(int i=0;i0)
当前记录--;
DisplayRec();
}
private void btnNEXT_单击(对象发送方,事件参数e)
{
如果(currentRec
1.txtNAME不应为空

要确定名称是null、空还是空白,可以使用方法

从MSDN:

指示指定的字符串是null、空还是仅由组成 空白字符的类型

试试这个:

if(!String.IsNullOrWhiteSpace(txtNAME.Text))
{    
  //continue    
}
else
{
 MessageBox.Show("Error");    
}
if(txtTELEPHONE.Text.Length>=10)
{    
  //continue    
}
else
{    
MessageBox.Show("Error");    
}
2.TXT电话应至少为10位

您可以使用字符串的
Length
属性来标识电话号码是否有10位数字

试试这个:

if(!String.IsNullOrWhiteSpace(txtNAME.Text))
{    
  //continue    
}
else
{
 MessageBox.Show("Error");    
}
if(txtTELEPHONE.Text.Length>=10)
{    
  //continue    
}
else
{    
MessageBox.Show("Error");    
}
3.txtEMAIL应采用带有“@”和“.”的电子邮件格式

为了验证EmailID,我建议您使用
RegEx
,而不是只检查
@
字符

试试这个:正则表达式

  Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
  Match match = regex.Match(txtEMAIL.Text);
  if (match.Success)
  {    
    //continue    
  }
  else
  {    
    MessageBox.Show("Error");    
  }
尝试以下操作:如果只想检查
@
字符

if(txtEMAIL.Text.Contains("@") && txtEMAIL.Text.Contains(".") )
{    
  //continue    
}
else
{    
MessageBox.Show("Error");    
}

对于第三次验证,可以使用 并通过

使用正则表达式将是更好的选择,因为它将为您提供修改条件的灵活性。stackoverflow的有用链接

< p>我会考虑通过属性使用和指定大量的需求,其余的是通过执行<代码> IValueAbabl Obj/<代码>提供的。将值添加到
Employee
对象的集合中,并使用
Validator.ValidateObject
方法对其运行验证。然后,您可以检查是否有由此返回的任何验证错误,并执行适当的操作

这也可能有助于XML序列化,因为您还可以根据需要使用XML属性对其进行注释以帮助实现这一点—甚至可以创建包含类
Employees
,并对其进行设置,以便可以使用
XmlSerializer
为您自动创建XML

public class Employee : IValidatableObject
{
   public int Id { get; set; }

   [Required]
   [StringLength(50)]
   public string Name { get; set; }

   [Required]
   public string JobTitle { get; set; }

   [Required]
   public string Address { get; set; }

   [Required]
   [Phone]
   public string TelephoneNumber { get; set; }

   [Required]
   [EmailAddress]
   public string Email { get; set;

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   {
       if (Id == 0)
       {
           yield return new ValidationResult("Employee Id must be greater than zero.", new [] { "Id" } );
       }
   }
}
public类雇员:IValidatableObject
{
公共int Id{get;set;}
[必需]
[长度(50)]
公共字符串名称{g
private void btnSAVE_Click(object sender, EventArgs e)
{
  if(validateEntries())
 {
  XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
  w.Formatting = Formatting.Indented;
  w.WriteStartDocument();
  w.WriteStartElement("employees");
  for (int i = 0; i < addCount; i++)
  {
      w.WriteStartElement("employees");

      w.WriteElementString("employeeID", employeeID[i].ToString());
      w.WriteElementString("employeeName", employeeName[i]);
      w.WriteElementString("jobTitle", jobTitle[i]);
      w.WriteElementString("address", address[i]);
      w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
      w.WriteElementString("email", email[i]);
      w.WriteEndElement();
  } w.WriteEndElement();
  w.WriteEndDocument();
  w.Close();
  Application.Exit();
}
}

   public bool VailidateEntries()
    {
      if (txtNAME.Text.Trim() == string.Empty)
        {
            MessageBox.Show("Name should not be empty");
            txtNAME.Focus();
            return false;
        }

      if (!(txtMailId.Text.Trim() == string.Empty))
      {
        if (!IsEmail(txtMailId.Text))
        {
            MessageBox.Show("Please enter valid Email Id's" );
            txtMailId.Focus();
            return false;
        }
     }

        if (!(txtPhone.Text.Trim() == string.Empty))
            {

                if (!IsPhone(txtPhone.Text))
                { 
                    MessageBox.Show("Invalid Phone Number");
                    txtPhone.Focus();
                    return false;
                }

            }
    }
    private bool IsEmail(string strEmail)
        {
            Regex validateEmail = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                       @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                       @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            return validateEmail.IsMatch(strEmail);
        }


        private bool IsPhone(String strPhone)
        {
            Regex validatePhone = new Regex("^([0-9]{3}|[0-9]{3})([0-9]{3}|[0-9]{3})[0-9]{4}$");
            return validatePhone.IsMatch(strPhone);
        }