2014-02-25 103 views
2

我想驗證輸入並處理這個程序中的異常。驗證以下內容:txtNAME中的字符串不應留空,txtTELEPHONE中的電話號碼至少應爲10位數字,並且txtEMAIL應採用帶「@」和「。」的電子郵件格式。如何驗證這些輸入,並在輸入錯誤的輸入的情況下處理異常?用C輸入驗證和異常#

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

您已經包括了很多不必要的代碼。如果你把這個問題提煉出適用於你的問題的代碼,人們會更願意提供幫助。 –

+0

儘管您可能認爲,電話號碼不是一個數字 - 它是一個數字字符序列。具體而言,根據您的位置以及是否包含國家/地區代碼,以數字形式存儲的電話號碼可能會溢出32位整數。最好將它作爲一個字符串來處理。 – tvanfosson

回答

3

txtName的不應該留空,

找出羯羊名稱爲空,空或空白符,你可以使用String.IsNullOrWhiteSpace()方法。

從MSDN:String.IsNullOrWhiteSpace()

指示指定字符串是否爲空,空的,或僅 的空白字符組成。

試試這個:

if(!String.IsNullOrWhiteSpace(txtNAME.Text)) 
{  
    //continue  
} 
else 
{ 
MessageBox.Show("Error");  
} 

2. txtTELEPHONE至少應爲10個位數,

您可以使用字符串的Length屬性標識閹電話號碼是有或不是10位數字。

試試這個: 「」

if(txtTELEPHONE.Text.Length>=10) 
{  
    //continue  
} 
else 
{  
MessageBox.Show("Error");  
} 

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");  
} 
+0

工作很輕鬆,謝謝。 – user3046541

1

我會考慮使用DataAnnotations,並通過屬性指定儘可能多的要求,結合通過實施IValidatableObject提供剩餘部分。將這些值添加到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" }); 
     } 
    } 
} 
0

你在找什麼是ErrorProvider。您可以使用這些來輕鬆驗證Windows窗體的安靜。我假設你經常使用設計模式安靜,所以這對你來說是最好的解決方案,但不是代碼質量。在工具欄中搜索ErrorProvider並將其添加到表單中。然後,您將在表單中將_ErrorProvider作爲對象提供。然後你只需要綁定驗證你的控制,例如:

txtTELEPHONE.Validating += ValidateName; 

而且功能:

private void ValidateName(object sender, CancelEventArgs e) 
{ 
    // early initialization of errorMsg to fill it if necessary 
    string errorMsg = null; 

    // check your textbox 
    if (String.IsNullOrEmpty(txtNAME.Text)) 
    { 
     errorMsg = "No name provided!"; 
    } 
    // this is the interesting part 
    _ErrorProvider.SetError(lblTELEPHONE, errorMsg); 
    e.Cancel = errorMsg != null; 
} 

使用圖標文本框的標籤的「_ErrorProvider.SetError」聯繫您的錯誤信息。如果用戶懸停在該圖標上,他或她可以看到錯誤消息。

有任何問題嗎?隨意問我:)在Save_click

2

()方法,調用該方法ValidateEntries()如下

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); 
     } 
+0

@ sindhu..Clean answer .. + 1 –

+0

我可以建議使用'string.IsNullOrWhitespace(someString)'而不是'someString.Trim()== string.Empty'。它的意圖要清晰得多,而且它在大型字符串上表現得更加出色。 –