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!

Let only positive numbers on texbox

Status
Not open for further replies.

ale77

Programmer
Joined
Jul 18, 2003
Messages
38
Location
US
I have a problem. I have a text input in a form and I want it to allow only numbers (no letters), a dot and non negative numbers. The problem is that is there is a dot in can only accept 9 characters, without a dot only 6 characters and cannot submit 0. Ex
135000
135000.56
 
Here is a function that I use to validate currency. It accepts only numbers, dot and minus sign so you can use it and modify it for your needs. Call the function by putting ...

onkeypress="onlyDigits()"

... in your input field.


Here is the function :


function onlyDigits()
{
var IS_PERIOD = 46;
var PERIOD_TYPED = false;
var IS_HYPHEN = 45;
var HYPHEN_TYPED = false;
var _ret = true;

if (window.event.keyCode == IS_PERIOD)
{
if (!PERIOD_TYPED)
PERIOD_TYPED = true;
else
{
window.event.keyCode = 0;
_ret = false;
}
}
if (window.event.keyCode == IS_HYPHEN)
{
if (!HYPHEN_TYPED)
HYPHEN_TYPED = true;
else
{
window.event.keyCode = 0;
_ret = false;
}
}
if (window.event.keyCode < 45 || window.event.keyCode > 57)
{
window.event.keyCode = 0;
_ret = false;
}
}//END ONLYDIGITS


Hope it work for you !!
 
How about something like this...
Code:
<form action=&quot;whatever&quot;>
<input type=&quot;text&quot; name=&quot;price&quot;>
<input type=&quot;button&quot; value=&quot;go&quot; onClick=&quot;checkPrice(this.form)&quot;>
</form>
...

function isPrice(p) 
{
  var filter = /^\d{1,6}(\.\d{2})?$/i;
  return filter.test(p);
}

function checkPrice(form)
{
  if (!isPrice(form.price.value)) {alert(&quot;Please enter valid price&quot;); return false;}
  else {form.submit();}
}
It hasn't been tested for syntax errors, but that's the general idea.

Sincerely,

Tom Anderson
Order amid Chaos, Inc.
 
Thanks for your suggestions, I used them but in a different way. I just have one question about var filter = /^\d{1,6}(\.\d{2})?$/i;
What does the character i at the end means???
 
ale77,

That's in case you have an &quot;uppercase&quot; number in there..
(Just kidding Tom);

It tells the expression to &quot;ignore&quot; case, normally used
with &quot;alpha&quot; chars'

And when you see &quot;g&quot; on the end that means &quot;global&quot;
 
Yup, it makes it case insensitive. Force of habit. You can leave the &quot;i&quot; off for this regex.

Sincerely,

Tom Anderson
Order amid Chaos, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top