Is there any Regular Expression to allow only one numeric in a textbox. ie, The user can type only one numeric (0 to 9) in that textbox.
Asked
Active
Viewed 2,113 times
1
-
1duplicates : [http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – Oliboy50 Jan 29 '14 at 13:42
-
This would work: `^\d{1}$` or `^[0-9]{1}$`, but only to validate input. – Daniel Jan 29 '14 at 13:44
3 Answers
5
Why regex when you have maxlength
Attribute and input type=number
maxlength="1"

Praveen
- 55,303
- 33
- 133
- 164
-
1
-
-
@techfoobar now-a-days html5 has become a part so they can use overcome by using [`html5shiv`](https://code.google.com/p/html5shiv/) right. Correct me if I'm wrong – Praveen Jan 29 '14 at 13:50
-
1@PraveenJeganathan - Yes, HTML5 wouldn't be a problem most of the time. Just pointing out still. – techfoobar Jan 29 '14 at 13:51
0
simple overwrite keydown event and allow/disalow keys
//delete, tab, enter, escape, backspace
var allowedKeys = [8,9,13,27,46];
jQuery("input[class=num]")
.attr('maxlength', 1)
.keydown(function(event) {
// Allow: , delete, tab, escape, enter and .
if ( jQuery.inArray(event.keyCode,allowedKeys) !== -1
|| (event.keyCode == 65 && event.ctrlKey === true)
|| (event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {
if ( event.shiftKey
|| (event.keyCode < 48
|| event.keyCode > 57)
&& (
event.keyCode < 96
|| event.keyCode > 105
)) {
event.preventDefault();
}
}
});

silly
- 7,789
- 2
- 24
- 37
0
I would do it like that
var regex = /^[0-9]{1,1}$/;
function checkInput(){
if(regex.test($('input').val()))
return true;
else
return false;
}

uzor
- 59
- 3