2011-04-12 59 views
2

我目前正在嘗試驗證我的ASP.NET表單。我需要確保用戶輸入了至少5個字符的密碼。Check request.form [「field」]字符串長度在ASP.net中不起作用

我做了檢查,以確保東西是有效的使用下面的代碼:

else if (Request.Form["txtPassword"] == "") 
{} 

我然後檢查這些字符不小於5通過使用下面的代碼:

if (Request.Form["txtPassword"].Length < 5) 
{} 

但是,當我運行窗體並提交它時,我不斷向用戶顯示有關密碼長度的錯誤,但我一直在從Visual Studio中獲取錯誤。在我嘗試提交它顯示的表單之前:

未將對象引用設置爲對象的實例。

這個錯誤只在我檢查長度的時候顯示,而不是在檢查字符串是空的時候顯示。

感謝您提供的任何幫助。

+0

您在ASP.NET生命週期的哪個階段檢查表單的內容(即調用Request.Form [「」]),爲什麼不檢查textBox文本屬性的長度? – 2011-04-12 21:51:55

回答

5

您有一個空引用異常。 Request.Form [「txtPassword」]返回null。這是發生了什麼事情:

string myString = null; 

// This is valid comparison because myString is a string object. 
// However, the string is not *empty*, it is null, thus it has *no* value. 
if(myString == "") 
{ 
    DoSomething(); 
} 

// This is not acceptable, as null.Length has no meaning whatsoever. 
// The expression compiles because the variable is of type string, 
// However, the string is null, so the "Length" property cannot be called. 
if(myString.Length < 5) 
{ 
    DoSomethingElse(); 
} 

您無法訪問空字符串的長度。嘗試使用此代替:

var myString = Request.Form["txtPassword"]; 

if(!String.IsNullOrEmpty(myString) && myString.Length < 5) 
{ 
    DoSomething(); 
} 

然而,下一個問題是爲什麼它是空的?也許你已經錯誤地將關聯的表單輸入命名爲「txtPassword」以外的東西,或者數據不是通過POST發送的。

+0

非常感謝您的幫助。這工作完美 – Boardy 2011-04-12 22:00:37

+1

請標記爲答案,然後 - 這是感謝的最佳形式:) – 2011-04-12 22:03:30

1

這可能意味着Request.Form["txtPassword"]爲空。我會首先檢查它是否存在。

0

由於您在空對象上調用Length屬性,所以Youy接收到該錯誤,在這種情況下,Request.Form [「txtPassword」]爲null,無法調用Length。

您可能想要確保您的文本框的ID爲「txtPassword」,請記住.net 4之前.net 4生成的客戶端ID如「ctl00_txtPassword」,併成爲表單字段,您可能需要輸入Request.Form [ ctl00_txtPassword「。

0

我有類似的問題。我試圖從一個項目發佈到另一個項目。由於我的要求,我堅持使用普通的HTML表單。值始終爲空。我用我的頭撞牆,直到我偶然發現了這個解決方案。

1:NO RUNAT = 「服務器」 表單中的頭

bad: <form id="form1" runat="server" action="http://yoursite.com/yourpage.aspx" method="post" > 
good: <form id="form1" action="http://yoursite.com/yourpage.aspx" method="post" > 

第二個標籤:

NET的HTML輸入框 淨HTML標籤:<input id="myinput" type="text" />

結束標記/>是問題。如果你刪除/它會工作。

bad: <input id="myinput" type="text" /> 
good: <input name="myinput" type="text" > 

第三:一定要使用「名」如果窗體標籤被放置在母版頁如屬性而不是「id」屬性

bad: <input id="myinput" type="text" /> 
good: <input name="myinput" type="text" > 
0

:的Site.Master,和你的形式要提交包含字段

< ASP:文本框ID = 「量」 名稱= 「量」 RUNAT = 「服務器」/>

並且實際上是的ContentPlaceHolder(ID =「MainConten內部t「),那麼如果你使用Request.Form [」amount「]它不起作用,並且總是顯示空值...因爲當頁面被渲染時,id實際上變成了」ctl00 $ MainContent $ amount「。因此,Request.Form [「ctl00 $ MainContent $ amount」]將起作用。