Dry run this function's code! - Input should be number!

They have: 11 posts

Joined: Jul 1999

I am trying to validate the input to three textboxes which are to hold the year value. The maxlength is 4. The problem is the function is accepting 'spaces + number' which it shouldn't. The input should only be numerical values. Please dry run the function's code and tell me where is the problem. Below is the code:

function chkyear(theyr) {

y=new Date();
limit=1900 + y.getYear()

if((theyr.length==0)¦¦(isNaN(theyr)))
{alert("Input valid year")}
else {
if(theyr.length!=4)
{theyr=19+theyr
if ((theyr > limit)¦¦(theyr < 1960))
{alert("You are not qualified!")}}
else {
if ((theyr > limit)¦¦(theyr < 1960))
{alert("You are not qualified!")}}
}
return theyr;
}
//-----------------------------

......
.....
for (i=1; i <=3; i++)
{chkyear(aform["yr"+i].value)}

This part of the code is calling the "chkyear" function. Sad

John Pollock's picture

He has: 628 posts

Joined: Mar 1999

Try using the parseInt() function to get just the number from the variable once you have it, try placing it at the beginning of the function you have:

function chkyear(parseInt(theyr)) {

y=new Date();
limit=1900 + y.getYear()

etc..

}

----------
Page Resource: http://www.pageresource.com
JavaScript City: http://www.javascriptcity.com

They have: 11 posts

Joined: Jul 1999

I get an error!
missing ) formal parameter

function chkyear(parseInt(theyr))
------------------------^

John Pollock's picture

He has: 628 posts

Joined: Mar 1999

Hmm...try this instead:

function chkyear(inyear) {

theyr=parseInt(inyear);

y=new Date();
limit=1900 + y.getYear()

etc..

}

----------
Page Resource: http://www.pageresource.com
JavaScript City: http://www.javascriptcity.com

They have: 11 posts

Joined: Jul 1999

Well, thank you very much for the help Mr. John.

However, parseInt() does return the integer part of a string. Unfortunately it can't detect an invalid string consisting of digits and other chars. For example, parseInt() returns "1" for the string "1as#" which is invalid input for a specified number field. I have modified the code. Below is the code:-

function chkyear(theyr) {
y=new Date();
limit=1900 + y.getYear()

if(theyr.length==0)
{alert("Input valid year")}
for (var i in theyr)
{if(isNaN(theyr[i]))
{found=1
if (found==1)
{alert("Input valid year")}
break}

else {
if(theyr.length < 4)
{theyr=19 + theyr
if ((theyr > limit)¦¦(theyr < 1960))
{alert("You are not qualified!")}}
else {
if ((theyr >= limit)¦¦(theyr < 1960))
{alert("You are not qualified!")}}
}}
}

It seem to work. Thanks again for the help.
Sundaram.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.