Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JavaScript Function to check numeric not working?

Status
Not open for further replies.

JohnBates

MIS
Feb 27, 2000
1,995
0
0
US
Hello JS experts -

I am trying to validate what has been entered into text boxes.... to be certain the user entered all numeric characters.

My Problem:
When I enter non-numeric characters, the isNum function is not detecting this (don't get the alert message in the ValidateInput function). Do I have an error in my code?

Thanks, John

Here is my code:


<SCRIPT language=&quot;JavaScript&quot;>
<!--
function ValidateInput()
{

if (!isNum(frmUser.Dept.value))
{
alert (&quot;Please enter your Department number - all digits&quot;)
frmUser.Dept.focus()
return false
}


if (!isNum(frmUser.PhoneW.value))
{
alert (&quot;Please enter your work phone number&quot;)
frmUser.PhoneW.focus()
return false
}

return true

}

// Is the entered value a Number ?
function isNum(entry)
{

alert (&quot;In isNum...value of number box is &quot;+ entry)
if (entry == &quot;&quot;)
{
return false

}

for (i=0; i<entry.length; i++)
{
if (entry.charat(i) < &quot;0&quot; )
{
return false
}
if (entry.charat(i) > &quot;9&quot; )
{
return false
}
}
return true
}
-->
</SCRIPT>


 
function isNum(str){
if (str.length == 0)
{
return false;
}
for (var i=0;i < str.length;i++)
{
if ((str.substring(i,i+1) < '0') || (str.substring(i,i+1) > '9'))
{
return false;
}
}
return true;
}//end isNum

try this
 
Hi!
To check the the entered text is integer or not you can also use isNaN() just like this:::

function checkIt()
{
var aStr = frmUser.PhoneW.value
if(isNaN(aStr))
{
alert(&quot;Please enter a integer value for telephone.&quot;)
frmUser.PhoneW.focus()
return false
}
}

Harsh.
 
Hi!

isNaN() method will return false if entered text is Integer or float(contains decimal).

But if you want to take only Integer values then firstly check with isNaN() then again check for indexOf(&quot;.&quot;) if it return -1 then entered text is Integer else not.
Like this::::

function checkIt()
{
var aStr = frmUser.PhoneW.value
if(isNaN(aStr))
{
if(aStr.indexOf(&quot;.&quot;) != -1)
{
alert(&quot;Please enter integer value for telephone.&quot;)
frmUser.PhoneW.focus()
return false
}
}
return true
}
Harsh.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top