2014-01-22 166 views
0

我試過驗證空字段的這段代碼,但是它在調用javascript時沒有正常工作,它沒有關注文本框,代碼將繼續執行。javascript中必填字段驗證

HTML代碼:

<asp:TextBox ID="txtholdername" runat="server" Width="60%"></asp:TextBox> 
<asp:TextBox ID="txtusername" runat="server" Width="60%"></asp:TextBox> 
<asp:ImageButton ID="btnsave" runat="server" OnClientClick="javascript:return validateRegistrationMaster();" ImageUrl="~/Images/save.png" /> 

腳本

function IsBlank(obj) { 
    if (obj) { 
     if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } 
     if ((obj.value.trim().length == 0) || (obj.value == null)) { 
      obj.focus(); 
      return false; 
     } 
     return true; 
    } 
} 
function validateRegistrationMaster() { 

    var Holder_Name = document.getElementById('<%= txtholdername.ClientID %>'); 
var username = document.getElementById('<%= txtusername.ClientID %>'); 
if ((!IsBlank(Holder_Name))) { 
     Holder_Name.focus(); 
     return false; 
    } 

    if ((!IsBlank(username))) { 
     username.focus(); 
     return false; 
    } return true; 
} 
+0

的jsfiddle你上面的代碼,如果你能 –

+0

我正在嘗試運行你的代碼,在Chrome瀏覽器。它可以正確運行。你有檢查另一個瀏覽器? –

+0

@KingJk我也在鉻上運行 –

回答

0

使用必填驗證,而不是自定義JavaScript,而使用Asp.Net控制。

例子:Click Here W3 Schools Link

代碼:

<asp:RequiredFieldValidator ControlToValidate="txtholdername" Text="The holder name field is required!" 
runat="server" /> 
<asp:RequiredFieldValidator ControlToValidate="txtusername" Text="The user namefield is required!" 
runat="server" />