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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

integer entry only

Status
Not open for further replies.

Tracey

Programmer
Oct 16, 2000
690
NZ
hi..

I would like to validate users input into a form, allowing only the number keys (eg no negatives or decimals)

I have found some basic code which traps out numbers using isNaN, but this allows -ve and decimals. could someone help me extend this to allow only +ve integers??? I have tried using this function on keypress, onkeyup etc but isnt quite right.
Code:
<script language=&quot;javascript&quot;>
<!--
function validate(txtbox)
{
    if (isNaN(txtbox.value) || txtbox.value==&quot;&quot;) {
        alert(&quot;Invalid Entry!&quot;);
        txtbox.focus();
    } else {
        alert(&quot;Do whatever you would do for a proper entry!&quot;);
    }
        
}
//-->
</script>
<form>
<input type=&quot;text&quot; name=&quot;entry&quot; onchange=&quot;validate(this.form.entry);&quot;>
<input type=&quot;button&quot;>
</form>
 

var valid=true, number=txtbox.value

//important to check for NaN first
if (isNaN(number)) valid=false;
//check for length, not null string, because number==0 is same as number==&quot;&quot;
else if (number.length=0) valid=false;
else if (Math.round(number)!=number) valid=false;
else if (number <= 0) valid=false;
//add more conditions here if wanted

if (!valid)
{
alert(&quot;Invalid Entry!&quot;);
txtbox.focus();
}
else
{
alert(&quot;Do whatever you would do for a proper entry!&quot;);
}
 
wow thanks trollacious, just what the doctor ordered
[2thumbsup]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top