PDA

View Full Version : number only txt box


david_stev
09-19-2003, 11:51 AM
I am trying to create a text box that only accepts numbers as input.

I have created the following function to achieve this.

function numberValidation(field, fieldName) {

var valid = "1234567890";
var ok = "yes";
var temp;

for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}

if (ok == "no") {
alert ("Only numbers are accepted in the "+fieldName+" text box");
field.focus();
field.select();
}
}

I call this using

<input type="text" name="EmployeeNo_ammend_<%=N%>" value="" onBlur"numberValidation(this, 'Employee Number')">

However when I click off the text box nothing happens.

Any help would be greatly appreciated.

Kor
09-19-2003, 01:01 PM
Try this kinda:


<head>
<script>
function bla() {
var field = document.forms[0].field1
var valo = new String();
var numere = "0123456789.";
var chars = field.value.split("");
for (i = 0; i < chars.length; i++) {
if (numere.indexOf(chars[i]) != -1) valo += chars[i];
else{alert("No non-numeric allowed!");}
}
if (field.value != valo) field.value = valo;
}
</script>
</head>
<body>
<form>
<input name="field1" type="text" id="field1" onkeyup="bla()">
</form>
</body>
</html>


My variant even blocks the other character to be written
On the other hand I think is better to use onkeyup event.

Caffeine
09-19-2003, 01:13 PM
On the other hand I think is better to use onkeyup event.

What if a user right-clicks the textbox, and paste some text in there ? I think it's better to use both onblur and onkeyup for that reason.

My point of view:
Throw an alert if the user tries to enter an illegal character [onkeyup] and maybe then disable the submit-button onblur, if the textarea/textfield contains an illegal character [ie if the user used rightclick->paste].

david_stev
09-19-2003, 02:26 PM
Did you not pick up on my deliberate mistake.
My function was fine it was the way that I was calling it that gave me bother I had written.

onBlur"numberValidation(this, 'Employee Number')">

instead of

onBlur="numberValidation(this, 'Employee Number')">

cheesebag
09-19-2003, 04:18 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>untitled</title>
</head>
<body>
<small>just numbers!</small>
<input type="text"
onkeyup="this.value=this.value.replace(/\D/g,'')"
onblur="this.value=this.value.replace(/\D/g,'')">
</body>
</html>

fredmv
09-19-2003, 04:18 PM
Always do this type of stuff on the server-side. I could use the JavaScript protocol and disable all event handlers on your textbox, paste contents into it, or simply disable JavaScript.

cheesebag
09-19-2003, 04:35 PM
Always do this type of stuff on the server-side.Why? Client-side validation/filtering isn't designed as a substitute for server input checking; it simply eases form use by performing basic validation at the user's computer, speeding thing up, saving server load and bandwith. It's not supposed to be secure, and shouldn't be used for mission-critical applications.

fredmv
09-19-2003, 04:37 PM
Yes, I actually agree with you. Especially when server-side technologies aren't available.

whammy
09-19-2003, 07:23 PM
That's a complicated way to do it when you can use regular expressions:

<script type="text/javascript">
<!--
function isNumericKey(e)
{
var k = document.all ? e.keyCode : e.which;
return ((k > 47 && k < 58) || k == 8 || k == 0);
}

function extractNumeric(str)
{
return str.replace(/\D/g,"");
}
// -->
</script>


isNumericKey() will prevent users with JavaScript enabled from entering anything but digits in a field.

extractNumeric() is used onchange, to clear out invalid characters if they are pasted into the field or put in by "auto complete".

Sample Usage:

<form id="example" action="javascript://">
<input type="text" onkeypress="return isNumericKey(event)" onchange="this.value=extractNumeric(this.value)" /> Numbers Only<br />
</form>

Kor
09-20-2003, 09:24 AM
...Yes, deffinitelly you have to use a server-side check also. This client-side check are for limited purposes only, and could not prevent an attack...

For instance, it is dangerous to allow more than 255 characters to be posted by an element of a form (for security reasons). You can do that using JavaScript, of course, but a malicious user can simply build his own local form, and use the action from the original page to send you a 256 character post...

Harry
09-28-2003, 09:38 AM
I use this and call the function with a onkey command

<script type="text/javascript">
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toUpperCase();

// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;

// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}

</script>

whammy
09-28-2003, 05:25 PM
Isn't that a really long way to do the same thing?

requestcode
09-29-2003, 01:45 PM
Wouldn't isNaN do the same thing?
function numberValidation(field, fieldName) {
if(isNaN(field.value))
{alert("Numbers only in the "+fieldName+" field")}
</script>

<input type="text" name="EmployeeNo_ammend_<%=N%>" value="" onKeyPress"numberValidation(this, 'Employee Number')">

whammy
09-30-2003, 01:13 AM
Nope. It won't. It's fairly sloppy code in my opinion. ;)

That's like using IsNumeric() in ASP/VBScript - it's effective if you just want to check for a number, but not effective against stuff like:

1.345

+1.3

-3.4

Which, if I'm not mistaken, will all return true using isNaN() (or IsNumeric() in VB/VBScript).

Not to mention some other values with "e" in them.

I've had to clean up some backend stuff at our company because the original developer used IsNumeric() for a lot of his validation when he _should have_ used a regular expression to throw an error if anything but digits was entered.

Suffice it to say that the client wasn't too happy that they were receiving values similar to those I mentioned above!!!

I find that it's good practice to test the HECK out of your validation code to make sure it's unbreakable.

Also, I agree with the comment above - I usually use JavaScript to try to reduce the load on the server; that doesn't mean I don't validate the data again on the server-side!

But by using client-side validation (especially with forms that are going to be accessed by a lot of people at once - for instance the result of an email broadcast asking people to renew their membership to something!), it really can help save bandwidth and reduce the load on the server since most people have javascript enabled.

That means 90% (or more) of the people that go to your form don't have to keep making repeated requests to your web server to validate their data, since the validation is happening client-side before submission. Think of the bandwidth saved!

liorean
09-30-2003, 07:10 AM
Neither of those returns true in the moz jsconsole (thus all of them are numbers), and neither does the e notation. But I gather what you want to do, is to single out the cases where there's no non-digits at all in the string. Why not simply chech for the regex /^\d+$/ which will match [start of string] [one or more digits] [end of string] with no pli (the correct plural of plus), mini (same for minus), spaces, commas, e:s, fulstops or other unwanted characters in it.

Kylena
09-30-2003, 09:30 AM
My solution is somewhat like whammy's

var f = document.forms[0]

var v = f.ExtNo.value
for ( i=0; i<v.length; i++) {
if ( ( v.charCodeAt(i)<48 || v.charCodeAt(i)>57 ) && v.charCodeAt(i) !== 44 ) {
alert ( "Extension Number must be numeric." );
f.ExtNo.focus();
return false
}
}

Though, I don't what code 44 is. I needed this so, copied from a helpful person. :D

Choopernickel
09-30-2003, 01:47 PM
44 is comma

HackerX
09-30-2003, 01:48 PM
Heres a twist on things


<html>
<head>
<title>Admin</title>
<script language="JavaScript">
function checkKey(obj)
{
var nums="0123456789";
o=document.getElementById(obj);
if(o.value.length==0) return;
lchar = o.value.substr(o.value.length-1,1)
if(nums.indexOf(lchar)==-1) o.value = o.value.substr(0,o.value.length-1);
}
</script>
</head>
<body>
<input type="text" onKeyUp="checkKey('num');" id="num" size="50" />
</body>
</html>

whammy
09-30-2003, 07:07 PM
liorean, that's why I posted this:

function extractNumeric(str)
{
return str.replace(/\D/g,"");
}

;)

Vincent Puglia
09-30-2003, 07:30 PM
Hi,

My 2 sense (cents :)
1) preliminary validation should be done client-side because of reasons stated above
2) using the onkey... event handler is a bad idea since most people are either looking at the keyboard or at a sheet of paper from which they are getting the data. They only look at the screen when they finish -- the implication being they will miss the alerts, especially if the sound is turned off.

Vinny

whammy
09-30-2003, 07:44 PM
Yeah, that's why I don't alert, I just return false and replace characters onblur (that's for auto-complete or copying and pasting, since there's not necessarily a keypress event with those!).

Vincent Puglia
09-30-2003, 07:51 PM
Hi whammy

give my regards to spookster & firepages
:)

Vinny