1

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>

4 Answers 4

3

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.