How to restrict my text field to numbers only and limit them in two with a single function.
Asked
Active
Viewed 2,527 times
0
-
3What do you mean "limit them in two" ? – mplungjan Apr 07 '11 at 08:26
-
2What do you have so far? – Kobi Apr 07 '11 at 08:27
-
1Text fields have a "maxsize" attribute, no JS needed. Check google for "textfield limit numbers" for a gazillion tutorials. – Apr 07 '11 at 08:28
-
http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Amr Elgarhy Apr 07 '11 at 08:29
-
1Perhaps the OP wants to dynamically change the maximum number of characters allowed in a field. I could conceive of a use for this. – Oren Hizkiya Apr 07 '11 at 08:36
-
Oren you got me... thanks i did not indite that one – theJava Apr 07 '11 at 08:37
-
@theJava -- There seems to be a lot of different interpreations being made of what you want. Perhaps you could edit the question to make it more clear exactly what you're trying to achieve. You may get more helpful answers. – Spudley Apr 07 '11 at 08:57
5 Answers
2
Since no one has suggested a regular expression, I will. :-)
var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
// number is one or two digits with optional leading minus
} else {
// it's not
}

RobG
- 142,382
- 31
- 172
- 209
1
<script type="text/javascript">
function ValidateField(FieldName){
// Get fields value
var FieldVal = document.GetElementById(FieldName).value;
// Check it's a number, and then check it's range is correct
// Alternatively you could do FieldVal.length
if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
alert("Valid!");
else
alert("Invalid");
}
</script>
<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>
I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.

okm
- 23,575
- 5
- 83
- 90

Tom Gullen
- 61,249
- 84
- 283
- 456
-
-
Because of minus symbols and plus symbols. -99 is 3 length, but OP might want that to pass as valid. – Tom Gullen Apr 07 '11 at 08:37
-
regarding the interpretation of allowing the minus sign: the question it too vague to make that kind of assumption. – Spudley Apr 07 '11 at 08:55
1
If you are using jquery:
$('#myTextAreaID').keydown(function(event) {
if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105

herostwist
- 3,778
- 1
- 26
- 34
-
thinking further this may be better: event.target.length >1 || String.fromCharCode(event.keyCode).match(/\D/); – herostwist Apr 07 '11 at 09:47