Page 1 of 1
how do i enter only numbers in a form field?
Posted: Wed May 11, 2005 9:23 pm
by mikewooten
i have a form with a few fields such as zip and phone. i only want the user to type in those fields numbers and not letters, and if the user enters letters, then the form will warn the user somehow to only enter number.
is there a function that will accomplish this or how is something like this accomplished?
what code would i have to use?
any help would be greatly appreciated.
thanks
Posted: Thu May 12, 2005 1:04 am
by s.dot
use a regex
PHP example:
Code: Select all
if(!eregi("^[_\.0-9-]+$",$_POST['zip'])){ die("Zip may only be numbers."); }
Posted: Thu May 12, 2005 3:31 am
by phpScott
on the client side as the first step you can do something like
Code: Select all
if(isNan(document.getElementById('zip').value)
{
alert('please enter numbers only');
document.getElementById('zip').focus();
}
in javascript
but stil validate on the server side as scrotaye suggests.
Posted: Fri May 13, 2005 8:57 am
by patrikG
A purely javascript/html solution:
Code: Select all
<script language="e;Javascript"e;>
function is_numeric(formfield){
var field=formfield.value
var regEx = /\D*/g;
return field.replace(regEx,"e;"e;);
}
</script>
<input type="e;text"e; onChange="e;this.value=is_numeric(this)"e; size="e;35"e;>
Posted: Fri May 13, 2005 9:59 am
by pickle
I think ~patrikG's solution is better than ~phpScott's, because ~patrikG's will actually remove the offending characters, whereas ~phpScott's won't
Posted: Fri May 13, 2005 10:20 am
by phpScott
I agree but I gave a js solution for what was being asked.
Oh well always next time to pull the stuning answer out of my hat.

Posted: Fri May 13, 2005 10:25 am
by patrikG
phpScott wrote:I agree but I gave a js solution for what was being asked.
Oh well always next time to pull the stuning answer out of my hat.

There is no next time when it comes to beer! Let's have a ~round:

Posted: Fri May 13, 2005 10:36 am
by phpScott
sussex is a bit far from B'ham(I think)
But after work I think I will.
Cheers mate.
Posted: Fri May 13, 2005 10:39 am
by patrikG
just a wee bit of a drive

But hey, we've earned it, the weekend is whiffable
Posted: Fri May 13, 2005 10:47 am
by JayBird
Not much of a head on that beer! Suppose that's how southern softies like it

Posted: Fri May 13, 2005 10:51 am
by patrikG
That's the first time I heard an English guy complain about not getting enough head.

Posted: Fri May 13, 2005 10:57 am
by phpScott
being a canuck living in the UK phpScott quickly walks the other way to the pub and starts to ignore where this conversation is going.

Posted: Fri May 13, 2005 11:00 am
by JayBird