Eyla
Eyla

Reputation: 5851

asp.net textbox with java script problem

I'm trying to check if asp.net textbox is empty or not using java script. my code working ok but if I enter only numbers will conder it empty so I have either enter letters and numbers or only letters.

Please advice.

here is my code

 <script type="text/javascript">
function check(){
  var txt = document.getElementById('<%=txt.ClientID%>').value;

              //(isNaN(cmbStateHome) == false

              if (isNaN(txt) == false) {
                  alert("Please enter some thing.");

              }
              else {alert("ok");}
          }
}
</script> 


 <asp:TextBox ID="txt" runat="server"></asp:TextBox>
                <asp:TextBox ID="txtZipCodeHome" runat="server" Style="top: 361px; left: 88px; position: absolute;

<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="check()">LinkButton</asp:LinkButton>

Upvotes: 1

Views: 1426

Answers (4)

Wallace Breza
Wallace Breza

Reputation: 4948

Take a look at using the <asp:RequiredFieldValidator /> server control. It will automatically apply a regex to the field and stop the user from submitting the form if they have not filled in the text box.

Ex)

<asp:TextBox id="TextBox1" runat="server"/>
<asp:RequiredFieldValidator id="req1" ControlToValidate="TextBox1" runat="server" />
<asp:LinkButton id="Button1" Text="Do Something" runat="server" />

Upvotes: 0

Kerido
Kerido

Reputation: 2940

Why don't you use if (txt.length == 0)?

Upvotes: 0

AaronS
AaronS

Reputation: 7703

isNAN is checking to see if the input is a number. ie: Not a Number.

Because of this, it will return false if you enter only numbers.

You should replace that check to see if the text is equal to an empty string.

Upvotes: 0

Phil Rykoff
Phil Rykoff

Reputation: 12087

replace

          if (isNaN(txt) == false) {

by

          if (txt == "") {

for isNan look here:

The isNaN function evaluates an argument to determine if it is "NaN" (not a number).

Upvotes: 3

Related Questions