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

number validation

Status
Not open for further replies.

stan8450

Programmer
May 3, 2002
16
CA
I am trying to do a simple validation for a text box(House_Sqft) to ensure the user enters in only numbers. The following code I have works if the user enters all letters (ersqgadsfg) but if the user types in a combination of letters and numbers (324324nn) it will accpet it. Any ideas?


var str_in = parseFloat(document.forms[0].House_Sqft.value)
if (isNaN(str_in)) {
alert("You must enter in a number for the house's approximate square feet");
document.forms[0].House_Sqft.value = "";
document.forms[0].House_Sqft.focus();
return false;
}
 
your validation will work if the first non-whitespace character in the textbox is a digit or a - sign followed by a digit..then it will read until it finds a non-digit or a second decimal place. I think this validation is fine, you just have to set the value of the textbox to the value you're finding

so do something like this:

var str_in = parseFloat(document.forms[0].House_Sqft.value)
if (isNaN(str_in)) {
alert("You must enter in a number for the house's approximate square feet");
document.forms[0].House_Sqft.value = "";
document.forms[0].House_Sqft.focus();
return false;
}
else{
document.forms[0].House_sqft.value = str_in;
return true;
}


this method is good incase the user accidentally hits 'q' before tab, or '\' before enter or something like that...it will just parse off the first number.

hope this is what you were looking for,

cheyney


 
To keep the user from even entering the characters in the first place, you could detect the key stroke and cancel it when it's not a number. I don't know if this will work in NS.

Code:
<script>
function numKeys(){
  return((event.keyCode>=49 && event.keyCode<=58)||(event.keyCode>=96 && event.keyCode<=105))
}
</script>
<input type=&quot;text&quot; onkeydown=&quot;return numKeys()&quot;>
 
You can encorporate adam's method into your textbox, but be aware you also need additional checking...although the numKeys() method will guard agains ctl+v pastes, it won't catch pastes executed through the file menu...so if a user has non-numeric data in the clipboard and your textbox selected and goes edit-paste, you'll get that data in the box. If you don't provide additional checking, you may still get a non-numeric string.

cheyney
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top