0

I want to show the 'valid' message if the variable value is

  • not numeric with length of 10
  • an empty string ("")

 

if(isNaN(num) && num !="" && num.length!=10)
{
    alert("invalid");
}
else
{
    alert("valid");
}

But this code shows 'digits which length is not 10' as valid. But whether it is numeric or not numeric, if its length is not 10 it should be invalid.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
chriz
  • 1,339
  • 2
  • 16
  • 32
  • `length` is a property valid for string. What do you mean by length here? The number of digits ? – mohkhan Jul 02 '13 at 07:04
  • If am nt wrong you want lenth not must be greater then 10 – Satinder singh Jul 02 '13 at 07:05
  • number of characters of text box value.. whether it is numeric or alphanumeric – chriz Jul 02 '13 at 07:07
  • if you just want to check for the length of string not equal to 10, irrespective of whether it is a number or not, then you just need one check and that is num.length!=10. – bazz Jul 02 '13 at 07:10
  • @satinder singh length should not be 10 an it should not be numeric. – chriz Jul 02 '13 at 07:13
  • @chriz: ok in your case you want lengh shud be less or greater then 10 is valid but not equal to 10 – Satinder singh Jul 02 '13 at 07:15
  • @bazz i don't want any alphabets in my string.. assume i am trying to take a mobile number.. it's length should be 10 and it should be numeric also.. so it should show valid only in this case.. – chriz Jul 02 '13 at 07:19
  • to check if numeric you can see that question http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric – thinklinux Jul 02 '13 at 07:21
  • @chriz: in prev above comment you said `@satinder singh length should not be 10 an it should not be numeric` and now `@bazz i don't want any alphabets in my string.` Pls clear you question WHAT YOU WANT ?? – Satinder singh Jul 02 '13 at 07:22
  • then your check should be if(!Nan(num) && num.length!=10) – bazz Jul 02 '13 at 07:22
  • ok.. i know that its working alone but when i add it with length property in condition, not showing expected result.. – chriz Jul 02 '13 at 07:23

2 Answers2

3

Your Condtion placement is wrong here.

isNaN(num) && num !=""
here, for num=1234,isNaN is false(that means it is number), but the num!="" will give true resulting in Invalid alert. 

Solution replace && with || for OR condtion.

Ruchan
  • 3,124
  • 7
  • 36
  • 72
0

Did you mean this:

if(is_nan(num) && num !="" && num.length<10)
{
alert("invalid");
}
else
{
alert("valid");
}

Otherwise if length is <9 or >10, you will get false.

In this case you will alert valid when your num is non-numeric, nun-empty string with length >= 10.

Brian
  • 4,958
  • 8
  • 40
  • 56