2014-01-15 101 views
1

我正在創建一個C#Windows註冊表單,這意味着用戶必須輸入他的用戶名,密碼和其他詳細信息才能註冊一個帳戶。當按鈕被點擊時,WinForm驗證不會被驗證

所以我使用兩個「ErrorProviders」事件的「驗證」事件爲每個文本框驗證文本框(一個用於錯誤,一個用於確定),以確保用戶名長度至少爲5個字符,密碼至少包含1大寫,1小寫等,電子郵件格式是正確的......你明白了。

以下是我的用戶名文本框中輸入驗證碼之一:

private void usrTxtBox_Validating(object sender, CancelEventArgs e) 
{ 
    if (string.IsNullOrEmpty(usrTxtBox.Text)) 
    { 
     usrOk.Clear(); 
     usrError.SetError(usrTxtBox, "field required!"); 
     count++; 
    } 
    else if (!Regex.IsMatch(usrTxtBox.Text, "</REGEX PATTERN/>")) 
    { 
     usrOk.Clear(); 
     usrError.SetError(usrTxtBox, "</ERROR MESSAGE/>"); 
     count++; 
    } 
    else 
    { 
     usrError.Clear(); 
     usrOk.SetError(usrTxtBox, "good to go"); 
     count = 0; 
    } 
} 

即重複每一個文本框(我的用戶名,密碼,姓名,電子郵件地址和聯繫電話,每一個不同的正則表達式

因此,正如大家可能知道的那樣,「驗證」事件只在文本框被「聚焦」然後「失去焦點」時纔會生效,因此,當我通過正確輸入所需的值單擊「註冊」對於第一個文本框,計數將等於0,因此,不會有錯誤。註冊按鈕的代碼點擊下面:

private void rgstr_Click(object sender, EventArgs e) 
{ 
    if (ValidateChildren()) 
    { 
     if (count != 0) 
     { 
      MessageBox.Show("check again"); 
     } 
     else if (count == 0) 
     { 
      MessageBox.Show("gd to go"); 
     } 
    } 
} 

我嘗試使用ValidateChildren強制驗證,但它不起作用。有沒有解決方案?還是有一個替代解決方案來驗證我的文本框?

+0

歡迎堆棧溢出!我編輯過你的標題。請參閱「應該在標題中是否包含」標籤?「,其中的共識是」不,他們不應該「。 http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles –

+0

啊,對不起,我會在將來的問題中留意。謝謝 – winston

+0

http://stackoverflow.com/questions/8915151/c-sharp-validating-input-for-textbox-on-winforms? 您確定取消該活動無效嗎? e.Cancel()?它可能會驗證正確,但對此沒有任何反應。 問題是什麼?確認錯誤的輸入或標記一切不正確? – wondra

回答

1

嘗試這個模式來驗證

private bool ValidateChildren() 
{ 
    bool IsValid = true; 
    // Clear error provider only once. 
    usrError.Clear(); 

    //use if condition for every condtion, dont use else-if 
    if (string.IsNullOrEmpty(usrTxtBox.Text.Trim())) 
     { 
     usrError.SetError(usrTxtBox, "field required!"); 
     IsValid =false;    
     } 

    if (!Regex.IsMatch(usrTxtBox.Text, "</REGEX PATTERN/>")) 
     {    
     usrError.SetError(usrTxtBox, "</ERROR MESSAGE/>"); 
     IsValid =false; 
     } 
    return IsValid ; 
    } 

和int按鈕點擊:

private void rgstr_Click(object sender, EventArgs e) 
    { 
     if (ValidateChildren()) 
     { 
      // valid 
     } 
     else 
     { 
     //Error will shown respective control with error provider 
     } 
    } 
+0

嗨,我從「私人布爾ValidateChildren()」,它說「不是所有的代碼路徑返回一個值」的錯誤。同樣,「bool IsValue」已分配,但其值始終未使用 – winston

+0

檢查更新後的代碼,我添加了return語句。 – Arshad

+0

嘿謝謝,它的工作原理,我自己雖然做了一些代碼更改。我改變了ValidateChildren()的名字,因爲它是一個會衝突的WinForm方法(?)。謝謝您的幫助!非常感激。 – winston