2012-03-05 85 views
-1

無論我輸入什麼數據都是正確的。我從文本框中獲取數據,用戶可以在其中輸入數據。我做錯了什麼? Utility.ValidName和Utility.Email返回true或false。來自表格的有效數據

檢查

string username = null; 
string email = null; 

username = textBox1.Text; 
email = textBox2.Text; 

bool vusernam = false; 
bool vemail = false; 

vusernam = Utility.ValidName (username); 
vemail = Utility.ValidEmail (email); 

if (vusernam == true && vemail == true) 
{ 
    Utility.WelcomeMessage (string.Format ("Hello {0}\nEMail: {1}\nWelcome!" , username , email)); 
    secondForm.Show (); 
    this.Hide (); 
} 
else 
{ 
    MessageBox.Show ("Please Enter a Username and Email Adress!"); 
} 

有效的用戶名和電子郵件

public static bool ValidEmail (string email) 
    { 
     string strTest = email; 
     Regex pattern = new Regex (@"(?<name>\S+)@(?<domain>\S+)"); 
     Match match = pattern.Match (strTest); 

     if (String.IsNullOrEmpty (email) || !match.Success) 
     { 
      Console.Write ("\nInvalid Email!"); 
     } 
     return true; 
    } 

    public static bool ValidName (string name) 
    { 
     string strTest = name; 


     if (String.IsNullOrEmpty (name)) 
     { 


      Console.Write ("\nInvalid Name!"); 


     } 
     return true; 
    } 
+3

可以顯示ValidName()和ValidEmail()的代碼嗎?這似乎是你的問題可能是 – psubsee2003 2012-03-05 22:24:09

+0

什麼問題?當你給他們不好的數據時,有效名稱和電子郵件會返回什麼?你有沒有使用調試器通過它? – 2012-03-05 22:24:32

回答

2

你總是返回true,不管是什麼。

在Console.Write後添加一個返回false。只輸出一條錯誤消息不會導致您的驗證失敗。

public static bool ValidName (string name) 
{ 
    string strTest = name; 

    if (String.IsNullOrEmpty (name)) 
    { 
     Console.Write ("\nInvalid Name!"); 
     return false; 
    } 
    return true; 
} 

旁註:

if (vusernam == true && vemail == true) 

可以減少到只需

if(vusernam && vemail) 

string strTest = name;似乎起不到任何作用的。

+0

大聲笑謝謝。我認爲,如果它進入了if狀態的內部,它會自動返回false。 – 2012-03-05 22:34:29

+2

1+用於提及將布爾值與另一個布爾值進行比較的代碼氣味。這通常表明不好的命名,也會使代碼膨脹。這會增加易讀性:'if(isValidUserName && isValidEmail)' – 2012-03-05 22:36:38

0

你的方法總是返回true的原因是因爲你只返回true。

public static bool ValidEmail (string email) 
{ 
    Regex pattern = new Regex(@"(?<name>\S+)@(?<domain>\S+)"); 
    Match match = pattern.Match(email); 

    return !String.IsNullOrEmpty(email) && match.Success 
} 

public static bool ValidName (string name) 
{ 
    return !String.IsNullOrEmpty(name); 
} 
相關問題