Is there a quick way to set an HTML text input (<input type=text />
) to only allow numeric keystrokes (plus '.')?
This question is related to
javascript
jquery
html
I tweaked it some, but it needs a lot more work to conform to the JavaScript weirding way.
function validateNumber(myEvent,decimal) {
var e = myEvent || window.event;
var key = e.keyCode || e.which;
if (e.shiftKey) {
} else if (e.altKey) {
} else if (e.ctrlKey) {
} else if (key === 48) { // 0
} else if (key === 49) { // 1
} else if (key === 50) { // 2
} else if (key === 51) { // 3
} else if (key === 52) { // 4
} else if (key === 53) { // 5
} else if (key === 54) { // 6
} else if (key === 55) { // 7
} else if (key === 56) { // 8
} else if (key === 57) { // 9
} else if (key === 96) { // Numeric keypad 0
} else if (key === 97) { // Numeric keypad 1
} else if (key === 98) { // Numeric keypad 2
} else if (key === 99) { // Numeric keypad 3
} else if (key === 100) { // Numeric keypad 4
} else if (key === 101) { // Numeric keypad 5
} else if (key === 102) { // Numeric keypad 6
} else if (key === 103) { // Numeric keypad 7
} else if (key === 104) { // Numeric keypad 8
} else if (key === 105) { // Numeric keypad 9
} else if (key === 8) { // Backspace
} else if (key === 9) { // Tab
} else if (key === 13) { // Enter
} else if (key === 35) { // Home
} else if (key === 36) { // End
} else if (key === 37) { // Left Arrow
} else if (key === 39) { // Right Arrow
} else if (key === 190 && decimal) { // decimal
} else if (key === 110 && decimal) { // period on keypad
// } else if (key === 188) { // comma
} else if (key === 109) { // minus
} else if (key === 46) { // Del
} else if (key === 45) { // Ins
} else {
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
And then it's called via:
$('input[name=Price]').keydown(function(myEvent) {
validateNumber(myEvent,true);
});
HTML5 has <input type=number>
, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.
If you are okay with using plugins, here is one I tested. It works well except for paste.
Here is a Demo http://jsfiddle.net/152sumxu/2
Code below (Lib pasted in-line)
<div id="plugInDemo" class="vMarginLarge">
<h4>Demo of the plug-in </h4>
<div id="demoFields" class="marginSmall">
<div class="vMarginSmall">
<div>Any Number</div>
<div>
<input type="text" id="anyNumber" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
// Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
(function(b) {
var c = { allowFloat: false, allowNegative: false};
b.fn.numericInput = function(e) {
var f = b.extend({}, c, e);
var d = f.allowFloat;
var g = f.allowNegative;
this.keypress(function(j) {
var i = j.which;
var h = b(this).val();
if (i>0 && (i<48 || i>57)) {
if (d == true && i == 46) {
if (g == true && a(this) == 0 && h.charAt(0) == "-") {
return false
}
if (h.match(/[.]/)) {
return false
}
}
else {
if (g == true && i == 45) {
if (h.charAt(0) == "-") {
return false
}
if (a(this) != 0) {
return false
}
}
else {
if (i == 8) {
return true
}
else {
return false
}
}
}
}
else {
if (i>0 && (i >= 48 && i <= 57)) {
if (g == true && h.charAt(0) == "-" && a(this) == 0) {
return false
}
}
}
});
return this
};
function a(d) {
if (d.selectionStart) {
return d.selectionStart
}
else {
if (document.selection) {
d.focus();
var f = document.selection.createRange();
if (f == null) {
return 0
}
var e = d.createTextRange(), g = e.duplicate();
e.moveToBookmark(f.getBookmark());
g.setEndPoint("EndToStart", e);
return g.text.length
}
}
return 0
}
}(jQuery));
$(function() {
$("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
});
</script>
Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).
Please find below mentioned solution. In this user can be able to enter only numeric
value, Also user can not be able to copy
, paste
, drag
and drop
in input.
Allowed Characters
0,1,2,3,4,5,6,7,8,9
Not allowed Characters and Characters through events
$(document).ready(function() {_x000D_
$('#number').bind("cut copy paste drag drop", function(e) {_x000D_
e.preventDefault();_x000D_
}); _x000D_
});_x000D_
function isNumberKey(evt) {_x000D_
var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57))_x000D_
return false;_x000D_
return true;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">
_x000D_
Let me know if it not works.
Here is a very short solution that doesn't use the deprecated keyCode
or which
, doesn't block any non input keys, and uses pure javascript. (Tested in Chromium 70.0.3533, Firefox 62.0, and Edge 42.17134.1.0)
HTML:
<input type="text" onkeypress="validate(event)">
JS:
function validate(ev) {
if (!ev) {
ev = window.event;
}
if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
return ev.preventDefault();
}
}
this also work for persian and arabic number :)
setNumericInput: function (event) {
var key = window.event ? event.keyCode : event.which
if (event.keyCode === 8 ||
(key >= 48 && key <= 57) ||
(key >= 1776 && key <= 1785)) {
return true
} else {
event.preventDefault()
}
}
One more example where you can add only numbers in the input field, can not letters
<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
Another easy way with jQuery:
$('.Numeric').bind('keydown',function(e){
if (e.which < 48 || e.which > 57)
return false;
return true;
})
Now just set your each inputs class to Numeric, like:
<input type="text" id="inp2" name="inp2" class='Numeric' />
Just an other variant with jQuery using
$(".numeric").keypress(function() {
return (/\d/.test(String.fromCharCode(event.which) ))
});
HTML5 supports regexes, so you could use this:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
Warning: Some browsers don't support this yet.
This removes any bad character instantly, allows only one dot, is short, and allows backspace, etc.:
$('.numberInput').keyup(function () {
s=$(this).val();
if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});
This is the easy solution
Replace .price-input input.quantity with the class of your input feild
$(".price-input input.quantity").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
just use type="number" now this attribute supporting in most of the browsers
<input type="number" maxlength="3" ng-bind="first">
<input type="tel"
onkeypress="return onlyNumberKey(event)">
in script tag
function onlyNumberKey(evt) {
// Only ASCII charactar in that range allowed
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
Here's a nice simple solution that I like to use:
function numeric_only (event, input) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(input).val () + String.fromCharCode (event.which));
}// numeric_only;
<input type="text" onkeypress="return numeric_only (event, this);" />
Explanation:
Using "event.which" - first determine if it's a printable character. If it isn't then allow it (for things like delete and backspace). Otherwise, concatinate the character to the end of the string and test it using the jQuery "isNumeric" function. This takes all of the tedium away from testing each individual character and also works for cut / paste scenarios.
If you want to get really cute then you can create a new HTML input type. Let's call it "numeric" so that you can have the tag:
<input type="numeric" />
which will only allow numeric characters. Just add the following "document.ready" command:
$(document).ready (function () {
$("input[type=numeric]").keypress (function (event) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(this).val () + String.fromCharCode (event.which));
});// numeric.keypress;
});// document.ready;
HTML doesn't care what type name you use - if it doesn't recognize it then it will use a textbox by default, so you can do this. Your editor may complain but, hey, that's its problem. No doubt puritans will freak out, but it works, is easy and so far it's been pretty robust for me.
This is the easy solution
Replace .price-input input.quantity with the class of your input feild
$(".price-input input.quantity").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
You can attach to the key down event and then filter keys according to what you need, for example:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
And the actual JavaScript handler would be:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
I realize an old post but i thought this could help someone. Recently I had to limit a text box to just 5 decimal places. In my case ALSO the users input had to be less than 0.1
<input type="text" value="" maxlength=7 style="width:50px" id="fmargin" class="formText" name="textfield" onkeyup="return doCheck('#fmargin',event);">
Here is the doCheck function
function doCheck(id,evt)
{
var temp=parseFloat($(id).val());
if (isNaN(temp))
temp='0.0';
if (temp==0)
temp='0.0';
$(id).val(temp);
}
Here is the same function except to force integer input
function doCheck(id,evt)
{
var temp=parseInt($(id).val());
if (isNaN(temp))
temp='0';
$(id).val(temp);
}
hope that helps someone
Use this DOM:
<input type = "text" onkeydown = "validate(event)"/>
And this script:
validate = function(evt)
{
if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
...OR this script, without indexOf, using two for
's...
validate = function(evt)
{
var CharValidate = new Array("08", "046", "039", "948", "235");
var number_pressed = false;
for (i = 0; i < 5; i++)
{
for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
{
if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
{
number_pressed = true;
}
}
}
if (number_pressed == false)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
I used the onkeydown attribute instead of onkeypress, because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the Google Chrome browser.
With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!
ASCII Code for TAB => 9
The first script have less code than the second, however, the array of ASCII characters must have all the keys.
The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:
NCount = 0
48 + NCount = 48
NCount + +
48 + NCount = 49
NCount + +
...
48 + NCount = 57
In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.
ASCII codes:
Regular expressions and the match function can work well for this situation. For instance, I used the following to validate 4 input boxes that served as coordinates on a graph. It works reasonably well.
function validateInput() {
if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
location.reload();
}
}
This is an improved function:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
This is the extended version of geowa4's solution. Supports min
and max
attributes. If the number is out of range, the previous value will be shown.
Usage: <input type=text class='number' maxlength=3 min=1 max=500>
function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
}
$(document).ready(function(){
$("input[type=text]").filter(".number,.NUMBER").on({
"focus":function(e){
$(e.target).data('oldValue',$(e.target).val());
},
"keypress":function(e){
e.target.oldvalue = e.target.value;
number(e);
},
"change":function(e){
var t = e.target;
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val(),10);
if( val<min || max<val)
{
alert("Error!");
$(t).val($(t).data('oldValue'));
}
}
});
});
If the inputs are dynamic use this:
$(document).ready(function(){
$("body").on("focus","input[type=text].number,.NUMBER",function(e){
$(e.target).data('oldValue',$(e.target).val());
});
$("body").on("keypress","input[type=text].number,.NUMBER",function(e){
e.target.oldvalue = e.target.value;
number(e);
});
$("body").on("change","input[type=text].number,.NUMBER",function(e){
var t = e.target
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val());
if( val<min || max<val)
{
alert("Error!");
$(t).val($(t).data('oldValue'));
}
});
});
I saw some great answers however I like them as small and as simple as possible, so maybe someone will benefit from it. I would use javascript Number()
and isNaN
functionality like this:
if(isNaN(Number(str))) {
// ... Exception it is NOT a number
} else {
// ... Do something you have a number
}
Hope this helps.
The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:
$(input).keypress(function (evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
var objRegex = /^-?\d*[\.]?\d*$/;
var val = $(evt.target).val();
if(!regex.test(key) || !objRegex.test(val+key) ||
!theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
};
});
Thanks guys this really help me!
I found the perfert one really useful for database.
function numonly(root){
var reet = root.value;
var arr1=reet.length;
var ruut = reet.charAt(arr1-1);
if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
}
}
}
Then add the eventhandler:
onkeyup="numonly(this);"
input type="number"
is an HTML5 attribute.
In the other case this will help you:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
Use:
<script>
function onlyNumber(id){
var DataVal = document.getElementById(id).value;
document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
}
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">
And if you want to update a value after press key, you can change onChange for onKeypress, onKeyDown or onKeyup. But event onKeypress doesn't running in any browsers.
My solution for a better user experience:
HTML
<input type="tel">
jQuery
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9','.']
return keys.indexOf(event.key) > -1
})
Details:
First of all, input types:
number
shows up/down arrows shrinking the actual input space, I find them ugly and are only useful if the number represents a quantity (things like phones, area codes, IDs... don't need them)
tel
provides similar browser validations of number without arrows
Using [number / tel] also helps showing numeric keyboard on mobile devices.
For the JS validation I ended up needing 2 functions, one for the normal user input (keypress) and the other for a copy+paste fix (change), other combinations would give me a terrible user experience.
I use the more reliable KeyboardEvent.key instead of the now deprecated KeyboardEvent.charCode
And depending of your browser support you can consider using Array.prototype.includes() instead of the poorly named Array.prototype.indexOf() (for true / false results)
And one more example, which works great for me:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
Also attach to keypress event
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
And HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
I've searched long and hard for a good answer to this, and we desperately need <input type="number"
, but short of that, these 2 are the most concise ways I could come up with:
<input type="text"
onkeyup="this.value=this.value.replace(/[^\d]/,'')">
If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!
<input type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )">
Here's a nice simple solution that I like to use:
function numeric_only (event, input) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(input).val () + String.fromCharCode (event.which));
}// numeric_only;
<input type="text" onkeypress="return numeric_only (event, this);" />
Explanation:
Using "event.which" - first determine if it's a printable character. If it isn't then allow it (for things like delete and backspace). Otherwise, concatinate the character to the end of the string and test it using the jQuery "isNumeric" function. This takes all of the tedium away from testing each individual character and also works for cut / paste scenarios.
If you want to get really cute then you can create a new HTML input type. Let's call it "numeric" so that you can have the tag:
<input type="numeric" />
which will only allow numeric characters. Just add the following "document.ready" command:
$(document).ready (function () {
$("input[type=numeric]").keypress (function (event) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(this).val () + String.fromCharCode (event.which));
});// numeric.keypress;
});// document.ready;
HTML doesn't care what type name you use - if it doesn't recognize it then it will use a textbox by default, so you can do this. Your editor may complain but, hey, that's its problem. No doubt puritans will freak out, but it works, is easy and so far it's been pretty robust for me.
JavaScript
function validateNumber(evt) {
var e = evt || window.event;
var key = e.keyCode || e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45) {
// input is VALID
}
else {
// input is INVALID
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
additional you could add comma, period and minus (,.-)
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
HTML
<input type="text" onkeydown="validateNumber(event);"/ >
I realize an old post but i thought this could help someone. Recently I had to limit a text box to just 5 decimal places. In my case ALSO the users input had to be less than 0.1
<input type="text" value="" maxlength=7 style="width:50px" id="fmargin" class="formText" name="textfield" onkeyup="return doCheck('#fmargin',event);">
Here is the doCheck function
function doCheck(id,evt)
{
var temp=parseFloat($(id).val());
if (isNaN(temp))
temp='0.0';
if (temp==0)
temp='0.0';
$(id).val(temp);
}
Here is the same function except to force integer input
function doCheck(id,evt)
{
var temp=parseInt($(id).val());
if (isNaN(temp))
temp='0';
$(id).val(temp);
}
hope that helps someone
Hope I am not beating a dead horse with an ugly stick here, but I am using this for my website quantity input, it allows only numbers from 1 to 99.
Try it: https://jsfiddle.net/83va5sb9/
<input min="1" type="text" id="quantity" name="quantity" value="1"
onKeyUp="numbersonly()">
<script>
function numbersonly() {
var str = document.getElementById("quantity").value
var newstr = ""
for (i = 0; i < str.length; i++) {
for (ii = 1; ii < 10; ii++) {
if (str.charAt(i).indexOf(ii) > -1) {
newstr += str.charAt(i)
}
}
}
if (newstr == "") {
newstr = 1
}
if (parseInt(newstr) > 99) {
newstr = 99
}
document.getElementById("quantity").value = newstr
}
</script>
I saw some great answers however I like them as small and as simple as possible, so maybe someone will benefit from it. I would use javascript Number()
and isNaN
functionality like this:
if(isNaN(Number(str))) {
// ... Exception it is NOT a number
} else {
// ... Do something you have a number
}
Hope this helps.
Regular expressions and the match function can work well for this situation. For instance, I used the following to validate 4 input boxes that served as coordinates on a graph. It works reasonably well.
function validateInput() {
if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
location.reload();
}
}
HTML5 has <input type=number>
, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.
I personally suggest to use the autoNumeric plugin from http://www.decorplanit.com/plugin/ - it supports all different variations like prefix/suffix handling, currency handling, negative value formatting, min, max etc.
A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.
This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.
The below script allows positive and negative numbers
1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed
var input = document.getElementById('number');_x000D_
input.onkeyup = input.onchange = enforceFloat;_x000D_
_x000D_
//enforce that only a float can be inputed_x000D_
function enforceFloat() {_x000D_
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;_x000D_
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;_x000D_
if (!valid.test(this.value)) {_x000D_
var n = this.value.match(number);_x000D_
this.value = n ? n[0] : '';_x000D_
}_x000D_
}
_x000D_
<input id="number" value="-3.1415" placeholder="Type a number" autofocus>
_x000D_
EDIT: I removed my old answer because I think it is antiquated now.
Hope I am not beating a dead horse with an ugly stick here, but I am using this for my website quantity input, it allows only numbers from 1 to 99.
Try it: https://jsfiddle.net/83va5sb9/
<input min="1" type="text" id="quantity" name="quantity" value="1"
onKeyUp="numbersonly()">
<script>
function numbersonly() {
var str = document.getElementById("quantity").value
var newstr = ""
for (i = 0; i < str.length; i++) {
for (ii = 1; ii < 10; ii++) {
if (str.charAt(i).indexOf(ii) > -1) {
newstr += str.charAt(i)
}
}
}
if (newstr == "") {
newstr = 1
}
if (parseInt(newstr) > 99) {
newstr = 99
}
document.getElementById("quantity").value = newstr
}
</script>
input type="number"
is an HTML5 attribute.
In the other case this will help you:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
You can replace the Shurok function with:
$(".numeric").keypress(function() {
return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.
JavaScript
function validateNumber(evt) {
var e = evt || window.event;
var key = e.keyCode || e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45) {
// input is VALID
}
else {
// input is INVALID
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
additional you could add comma, period and minus (,.-)
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
HTML
<input type="text" onkeydown="validateNumber(event);"/ >
Call this function when ready to validate what ever. I used a textbox here
In my HTML:
<input type="button" value="Check IT!" onclick="check(document.getElementById('inputboxToValidate').value);" />
In my JavaScript code:
function check(num){
var onlynumbers = true
for (var i = 0; i < (num.length - 1); i++) {
if (num.substr(i, 1) != "0" || num.substr(i, 1) != "1" || num.substr(i, 1) != "2" || num.substr(i, 1) != "3" || num.substr(i, 1) != "4" || num.substr(i, 1) != "5" || num.substr(i, 1) != "6" || num.substr(i, 1) != "7" || num.substr(i, 1) != "8" || num.substr(i, 1) != "9") {
alert("please make sure that only numbers have been entered in the Quantaty box");
onlynumbers = false
}
}
if (onlynumbers == true) {
//Execute Code
}
}
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
I personally suggest to use the autoNumeric plugin from http://www.decorplanit.com/plugin/ - it supports all different variations like prefix/suffix handling, currency handling, negative value formatting, min, max etc.
The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:
$(input).keypress(function (evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
var objRegex = /^-?\d*[\.]?\d*$/;
var val = $(evt.target).val();
if(!regex.test(key) || !objRegex.test(val+key) ||
!theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
};
});
If you are trying on angular this might help
To get the input as number (with a decimal point) then
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
Now this will not update the value in model correctly to explicitly change the value of model too add this
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" (change)="data = $event.target.value">
The change event will fire after the value in the model has been updated so it can be used with reactive forms as well.
This is the extended version of geowa4's solution. Supports min
and max
attributes. If the number is out of range, the previous value will be shown.
Usage: <input type=text class='number' maxlength=3 min=1 max=500>
function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
}
$(document).ready(function(){
$("input[type=text]").filter(".number,.NUMBER").on({
"focus":function(e){
$(e.target).data('oldValue',$(e.target).val());
},
"keypress":function(e){
e.target.oldvalue = e.target.value;
number(e);
},
"change":function(e){
var t = e.target;
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val(),10);
if( val<min || max<val)
{
alert("Error!");
$(t).val($(t).data('oldValue'));
}
}
});
});
If the inputs are dynamic use this:
$(document).ready(function(){
$("body").on("focus","input[type=text].number,.NUMBER",function(e){
$(e.target).data('oldValue',$(e.target).val());
});
$("body").on("keypress","input[type=text].number,.NUMBER",function(e){
e.target.oldvalue = e.target.value;
number(e);
});
$("body").on("change","input[type=text].number,.NUMBER",function(e){
var t = e.target
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val());
if( val<min || max<val)
{
alert("Error!");
$(t).val($(t).data('oldValue'));
}
});
});
You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.
You can replace the Shurok function with:
$(".numeric").keypress(function() {
return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
Most answers here all have the weakness of using key- events.
Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.
This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.
function forceNumeric(){
var $input = $(this);
$input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);
HTML5 has <input type=number>
, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.
this also work for persian and arabic number :)
setNumericInput: function (event) {
var key = window.event ? event.keyCode : event.which
if (event.keyCode === 8 ||
(key >= 48 && key <= 57) ||
(key >= 1776 && key <= 1785)) {
return true
} else {
event.preventDefault()
}
}
Use this DOM:
<input type = "text" onkeydown = "validate(event)"/>
And this script:
validate = function(evt)
{
if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
...OR this script, without indexOf, using two for
's...
validate = function(evt)
{
var CharValidate = new Array("08", "046", "039", "948", "235");
var number_pressed = false;
for (i = 0; i < 5; i++)
{
for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
{
if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
{
number_pressed = true;
}
}
}
if (number_pressed == false)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
I used the onkeydown attribute instead of onkeypress, because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the Google Chrome browser.
With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!
ASCII Code for TAB => 9
The first script have less code than the second, however, the array of ASCII characters must have all the keys.
The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:
NCount = 0
48 + NCount = 48
NCount + +
48 + NCount = 49
NCount + +
...
48 + NCount = 57
In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.
ASCII codes:
A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:
$('input.numeric').live('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.
JavaScript code:
function validate(evt)
{
if(evt.keyCode!=8)
{
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
}
HTML code:
<input type='text' name='price' value='0' onkeypress='validate(event)'/>
works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)
Code bellow will also check for PASTE event.
Uncomment "ruleSetArr_4" and add(concate) to "ruleSetArr" to allow FLOAT numbers.
Easy copy/paste function. Call it with your input element in parameter.
Example: inputIntTypeOnly($('input[name="inputName"]'))
function inputIntTypeOnly(elm){_x000D_
elm.on("keydown",function(event){_x000D_
var e = event || window.event,_x000D_
key = e.keyCode || e.which,_x000D_
ruleSetArr_1 = [8,9,46], // backspace,tab,delete_x000D_
ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57], // top keyboard num keys_x000D_
ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys_x000D_
ruleSetArr_4 = [17,67,86], // Ctrl & V_x000D_
//ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values_x000D_
ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4); // merge arrays of keys_x000D_
_x000D_
if(ruleSetArr.indexOf() !== "undefined"){ // check if browser supports indexOf() : IE8 and earlier_x000D_
var retRes = ruleSetArr.indexOf(key);_x000D_
} else { _x000D_
var retRes = $.inArray(key,ruleSetArr);_x000D_
};_x000D_
if(retRes == -1){ // if returned key not found in array, return false_x000D_
return false;_x000D_
} else if(key == 67 || key == 86){ // account for paste events_x000D_
event.stopPropagation();_x000D_
};_x000D_
_x000D_
}).on('paste',function(event){_x000D_
var $thisObj = $(this),_x000D_
origVal = $thisObj.val(), // orig value_x000D_
newVal = event.originalEvent.clipboardData.getData('Text'); // paste clipboard value_x000D_
if(newVal.replace(/\D+/g, '') == ""){ // if paste value is not a number, insert orig value and ret false_x000D_
$thisObj.val(origVal);_x000D_
return false;_x000D_
} else {_x000D_
$thisObj.val(newVal.replace(/\D+/g, ''));_x000D_
return false;_x000D_
};_x000D_
_x000D_
});_x000D_
};_x000D_
_x000D_
var inptElm = $('input[name="inputName"]');_x000D_
_x000D_
inputIntTypeOnly(inptElm);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input type="text" name="inputName" value="1">
_x000D_
One more example where you can add only numbers in the input field, can not letters
<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use <input type="number">
.
When it comes to fool-proofing UX, one should always try to keep a reference point for the 'user's intelligence'.
While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.
Also, for forms, validation and error message display are almost a necessity. So, the provisions might already be there. Here's the algorithm:
On losing-focus or form-submission, do following.
1.1. Read content from the input and apply parseFloat to result
1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584".
1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2.
1.4. Else, do nothing.
This method also gives you the added advantage of performing validations based on minimum value, maximum value, decimal places, etc if necessary. Just have to do these operations on the result after step 1.2.
Disadvantages:
The input will allow the user to enter any value until the focus is lost or the form is submitted. But if the instructions on filling the field were clear enough, in 90% of the cases this might not come up.
If step 1.3 is used to display a warning, it might be overlooked by the user and might result in unintentional input submission. Throwing an error or displaying the warning properly would solve this.
Speed. This might be slower in microseconds than the regex method.
Advantages: Assuming the user have basic knowledge to read and understand,
Highly customizable with options.
Works cross browser and independent of language.
Makes use of already available features in a form to display errors and warnings.
Give the input field a class (<input class="digit" ...>
) and use jquery as below .
jQuery(document).ready(function () {
jQuery('input.digit').live('input keyup',function(e){ jQuery(this).val(jQuery(this).val().replace( /[^\d]/g ,'')); });
});
Above code also works to disable special characters in Ctrl+V
strokes and right click
strokes also.
function digitsOnly(obj) {
obj.value = obj.value.replace(/\D/g, "");
}
and in the element
<input type="text" onkeyup="digitsOnly(this);" />
<input type="tel"
onkeypress="return onlyNumberKey(event)">
in script tag
function onlyNumberKey(evt) {
// Only ASCII charactar in that range allowed
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
I've searched long and hard for a good answer to this, and we desperately need <input type="number"
, but short of that, these 2 are the most concise ways I could come up with:
<input type="text"
onkeyup="this.value=this.value.replace(/[^\d]/,'')">
If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!
<input type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )">
Here is a simple one which allows for exactly one decimal, but no more:
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />
_x000D_
I couldn't find a clear answer, that doesn't loop over the whole string every time, so here:
document.querySelectorAll("input").forEach(input => {
input.addEventListener("input", e => {
if (isNaN(Number(input.value[input.value.length-1])) && input.value[input.value.length-1] != '.') {
input.value = input.value.slice(0, -1);
}
})
});
No regex, this goes over the last character every time you type and slices it if it's not a number or period.
I finished using this function:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"
This works well in IE and Chrome, I don´t know why it´s not work well in firefox too, this function block the tab key in Firefox.
For the tab key works fine in firefox add this:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
A easy way to resolve this problem is implementing a jQuery function to validate with regex the charaters typed in the textbox for example:
Your html code:
<input class="integerInput" type="text">
And the js function using jQuery
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
$(function() {_x000D_
$('.integerInput').on('input', function() {_x000D_
this.value = this.value_x000D_
.replace(/[^\d]/g, '');// numbers and decimals only_x000D_
_x000D_
});_x000D_
});
_x000D_
<script_x000D_
src="https://code.jquery.com/jquery-2.2.4.min.js"_x000D_
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="_x000D_
crossorigin="anonymous">_x000D_
</script>_x000D_
_x000D_
<input type="text" class="integerInput"/>_x000D_
_x000D_
_x000D_
_x000D_
When it comes to fool-proofing UX, one should always try to keep a reference point for the 'user's intelligence'.
While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.
Also, for forms, validation and error message display are almost a necessity. So, the provisions might already be there. Here's the algorithm:
On losing-focus or form-submission, do following.
1.1. Read content from the input and apply parseFloat to result
1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584".
1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2.
1.4. Else, do nothing.
This method also gives you the added advantage of performing validations based on minimum value, maximum value, decimal places, etc if necessary. Just have to do these operations on the result after step 1.2.
Disadvantages:
The input will allow the user to enter any value until the focus is lost or the form is submitted. But if the instructions on filling the field were clear enough, in 90% of the cases this might not come up.
If step 1.3 is used to display a warning, it might be overlooked by the user and might result in unintentional input submission. Throwing an error or displaying the warning properly would solve this.
Speed. This might be slower in microseconds than the regex method.
Advantages: Assuming the user have basic knowledge to read and understand,
Highly customizable with options.
Works cross browser and independent of language.
Makes use of already available features in a form to display errors and warnings.
You can attach to the key down event and then filter keys according to what you need, for example:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
And the actual JavaScript handler would be:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
2 solutions:
Use a form validator (for example with jQuery validation plugin)
Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("^\d*\.?\d*$");
if (!regExpr.test(field.value)) {
// Case of error
field.value = "";
}
}
</script>
<input type="text" ... onblur="testField(this);"/>
If you are okay with using plugins, here is one I tested. It works well except for paste.
Here is a Demo http://jsfiddle.net/152sumxu/2
Code below (Lib pasted in-line)
<div id="plugInDemo" class="vMarginLarge">
<h4>Demo of the plug-in </h4>
<div id="demoFields" class="marginSmall">
<div class="vMarginSmall">
<div>Any Number</div>
<div>
<input type="text" id="anyNumber" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
// Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
(function(b) {
var c = { allowFloat: false, allowNegative: false};
b.fn.numericInput = function(e) {
var f = b.extend({}, c, e);
var d = f.allowFloat;
var g = f.allowNegative;
this.keypress(function(j) {
var i = j.which;
var h = b(this).val();
if (i>0 && (i<48 || i>57)) {
if (d == true && i == 46) {
if (g == true && a(this) == 0 && h.charAt(0) == "-") {
return false
}
if (h.match(/[.]/)) {
return false
}
}
else {
if (g == true && i == 45) {
if (h.charAt(0) == "-") {
return false
}
if (a(this) != 0) {
return false
}
}
else {
if (i == 8) {
return true
}
else {
return false
}
}
}
}
else {
if (i>0 && (i >= 48 && i <= 57)) {
if (g == true && h.charAt(0) == "-" && a(this) == 0) {
return false
}
}
}
});
return this
};
function a(d) {
if (d.selectionStart) {
return d.selectionStart
}
else {
if (document.selection) {
d.focus();
var f = document.selection.createRange();
if (f == null) {
return 0
}
var e = d.createTextRange(), g = e.duplicate();
e.moveToBookmark(f.getBookmark());
g.setEndPoint("EndToStart", e);
return g.text.length
}
}
return 0
}
}(jQuery));
$(function() {
$("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
});
</script>
For those of you that like one-liners.
string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
I use this code on an input type="text", and with AngularJS to activate on keypress, but you can use jQuery if like. Just put this code into a function that activates on a keypress some way.
It only allows digits, digits + decimal, digits + decimal + digits.
CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";
testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";
testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";
testFour = "622632463.23464236326324363"
=> "622632463.23";
This was built for US currency, but it can be changed to allow more than two decimals past first decimal place as in the following...
CHANGED CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');
testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";
:)
2 solutions:
Use a form validator (for example with jQuery validation plugin)
Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("^\d*\.?\d*$");
if (!regExpr.test(field.value)) {
// Case of error
field.value = "";
}
}
</script>
<input type="text" ... onblur="testField(this);"/>
just use type="number" now this attribute supporting in most of the browsers
<input type="number" maxlength="3" ng-bind="first">
A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:
$('input.numeric').live('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.
I couldn't find a clear answer, that doesn't loop over the whole string every time, so here:
document.querySelectorAll("input").forEach(input => {
input.addEventListener("input", e => {
if (isNaN(Number(input.value[input.value.length-1])) && input.value[input.value.length-1] != '.') {
input.value = input.value.slice(0, -1);
}
})
});
No regex, this goes over the last character every time you type and slices it if it's not a number or period.
var userName = document.querySelector('#numberField');
userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {
var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
this.value = newValue;
}
_x000D_
<input type="text" id="numberField">
_x000D_
A easy way to resolve this problem is implementing a jQuery function to validate with regex the charaters typed in the textbox for example:
Your html code:
<input class="integerInput" type="text">
And the js function using jQuery
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
$(function() {_x000D_
$('.integerInput').on('input', function() {_x000D_
this.value = this.value_x000D_
.replace(/[^\d]/g, '');// numbers and decimals only_x000D_
_x000D_
});_x000D_
});
_x000D_
<script_x000D_
src="https://code.jquery.com/jquery-2.2.4.min.js"_x000D_
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="_x000D_
crossorigin="anonymous">_x000D_
</script>_x000D_
_x000D_
<input type="text" class="integerInput"/>_x000D_
_x000D_
_x000D_
_x000D_
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Call this function when ready to validate what ever. I used a textbox here
In my HTML:
<input type="button" value="Check IT!" onclick="check(document.getElementById('inputboxToValidate').value);" />
In my JavaScript code:
function check(num){
var onlynumbers = true
for (var i = 0; i < (num.length - 1); i++) {
if (num.substr(i, 1) != "0" || num.substr(i, 1) != "1" || num.substr(i, 1) != "2" || num.substr(i, 1) != "3" || num.substr(i, 1) != "4" || num.substr(i, 1) != "5" || num.substr(i, 1) != "6" || num.substr(i, 1) != "7" || num.substr(i, 1) != "8" || num.substr(i, 1) != "9") {
alert("please make sure that only numbers have been entered in the Quantaty box");
onlynumbers = false
}
}
if (onlynumbers == true) {
//Execute Code
}
}
Please find below mentioned solution. In this user can be able to enter only numeric
value, Also user can not be able to copy
, paste
, drag
and drop
in input.
Allowed Characters
0,1,2,3,4,5,6,7,8,9
Not allowed Characters and Characters through events
$(document).ready(function() {_x000D_
$('#number').bind("cut copy paste drag drop", function(e) {_x000D_
e.preventDefault();_x000D_
}); _x000D_
});_x000D_
function isNumberKey(evt) {_x000D_
var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57))_x000D_
return false;_x000D_
return true;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">
_x000D_
Let me know if it not works.
This is an improved function:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
2 solutions:
Use a form validator (for example with jQuery validation plugin)
Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("^\d*\.?\d*$");
if (!regExpr.test(field.value)) {
// Case of error
field.value = "";
}
}
</script>
<input type="text" ... onblur="testField(this);"/>
Below function will check for every input char if it is number.
numeric: value => {
let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
console.log(numset.has(value.substring(value.length - 1, value.length)));
}
I tweaked it some, but it needs a lot more work to conform to the JavaScript weirding way.
function validateNumber(myEvent,decimal) {
var e = myEvent || window.event;
var key = e.keyCode || e.which;
if (e.shiftKey) {
} else if (e.altKey) {
} else if (e.ctrlKey) {
} else if (key === 48) { // 0
} else if (key === 49) { // 1
} else if (key === 50) { // 2
} else if (key === 51) { // 3
} else if (key === 52) { // 4
} else if (key === 53) { // 5
} else if (key === 54) { // 6
} else if (key === 55) { // 7
} else if (key === 56) { // 8
} else if (key === 57) { // 9
} else if (key === 96) { // Numeric keypad 0
} else if (key === 97) { // Numeric keypad 1
} else if (key === 98) { // Numeric keypad 2
} else if (key === 99) { // Numeric keypad 3
} else if (key === 100) { // Numeric keypad 4
} else if (key === 101) { // Numeric keypad 5
} else if (key === 102) { // Numeric keypad 6
} else if (key === 103) { // Numeric keypad 7
} else if (key === 104) { // Numeric keypad 8
} else if (key === 105) { // Numeric keypad 9
} else if (key === 8) { // Backspace
} else if (key === 9) { // Tab
} else if (key === 13) { // Enter
} else if (key === 35) { // Home
} else if (key === 36) { // End
} else if (key === 37) { // Left Arrow
} else if (key === 39) { // Right Arrow
} else if (key === 190 && decimal) { // decimal
} else if (key === 110 && decimal) { // period on keypad
// } else if (key === 188) { // comma
} else if (key === 109) { // minus
} else if (key === 46) { // Del
} else if (key === 45) { // Ins
} else {
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
And then it's called via:
$('input[name=Price]').keydown(function(myEvent) {
validateNumber(myEvent,true);
});
For those of you that like one-liners.
string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
I use this code on an input type="text", and with AngularJS to activate on keypress, but you can use jQuery if like. Just put this code into a function that activates on a keypress some way.
It only allows digits, digits + decimal, digits + decimal + digits.
CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";
testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";
testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";
testFour = "622632463.23464236326324363"
=> "622632463.23";
This was built for US currency, but it can be changed to allow more than two decimals past first decimal place as in the following...
CHANGED CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');
testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";
:)
You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.
Another easy way with jQuery:
$('.Numeric').bind('keydown',function(e){
if (e.which < 48 || e.which > 57)
return false;
return true;
})
Now just set your each inputs class to Numeric, like:
<input type="text" id="inp2" name="inp2" class='Numeric' />
Just an other variant with jQuery using
$(".numeric").keypress(function() {
return (/\d/.test(String.fromCharCode(event.which) ))
});
Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).
HTML5 has <input type=number>
, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.
Here is a simple one which allows for exactly one decimal, but no more:
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />
_x000D_
You can attach to the key down event and then filter keys according to what you need, for example:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
And the actual JavaScript handler would be:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
And one more example, which works great for me:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
Also attach to keypress event
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
And HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
I might have another (simple) workaround for this...
Since String.fromCharCode(key) returns weird things upon AZERTY keyboard (numerical keypad returns code as g for 1, and 1 for & character ..
I've realized catching the final value on keyup within the input to reset it to an arbitrary value is a simpler, lightweight & bugproof method (could also be done via some regex ... to keep decimals and so on ... don't have to filter other Ctrl, Home, Del, and Enter events...)
Usage with jq :
<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>
Onkeyup attribute:
<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>
Yes, HTML5 does. Try this code (w3school):
<!DOCTYPE html>
<html>
<body>
<form action="">
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
<input type="submit" />
</form>
</body>
</html>
Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).
Most answers here all have the weakness of using key- events.
Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.
This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.
function forceNumeric(){
var $input = $(this);
$input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);
I opted to use a combination of the two answers mentioned here i.e.
<input type="number" />
and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
<input type="text" onkeypress="return isNumberKey(event);">
If you are trying on angular this might help
To get the input as number (with a decimal point) then
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
Now this will not update the value in model correctly to explicitly change the value of model too add this
<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" (change)="data = $event.target.value">
The change event will fire after the value in the model has been updated so it can be used with reactive forms as well.
I use the jquery.inputmask.js library you can download from NuGet. More specifically I use jquery.inputmask.regex.extensions.js that comes with it.
I give the input element a class, in this case reg
:
<input type="number" id="WorkSrqNo" name="WorkSrqNo" maxlength="6" class="reg"/>
And then in JavaScript I set the mask:
var regexDigitsOnly = "^[0-9]*$";
$('input.reg').inputmask('Regex', { regex: regexDigitsOnly });
This is for digits only, but you can alter the regular expression to accept ".".
By using this it is impossible to enter characters that are not digits. It is useful to have these inputmask libraries for general formatting.
If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use <input type="number">
.
So simple....
// In a JavaScript function (can use HTML or PHP).
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
In your form input:
<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>
With input max. (These above allows for a 12-digit number)
You can use pattern for this:
<input id="numbers" pattern="[0-9.]+" type="number">
Here you can see the complete mobile website interface tips.
function digitsOnly(obj) {
obj.value = obj.value.replace(/\D/g, "");
}
and in the element
<input type="text" onkeyup="digitsOnly(this);" />
I was looking for a way to block an input of numbers, then, as I did not find it in answers, this code worked fine for me.
I just need to input it in the onkeypress event.
If you need just to block an input of numbers, I believe this will work fine.
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"
You can also compare input value (which is treated as string by default) to itself forced as numeric, like:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
However, you need to bind that to event like keyup etc.
var userName = document.querySelector('#numberField');
userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {
var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
this.value = newValue;
}
_x000D_
<input type="text" id="numberField">
_x000D_
I might have another (simple) workaround for this...
Since String.fromCharCode(key) returns weird things upon AZERTY keyboard (numerical keypad returns code as g for 1, and 1 for & character ..
I've realized catching the final value on keyup within the input to reset it to an arbitrary value is a simpler, lightweight & bugproof method (could also be done via some regex ... to keep decimals and so on ... don't have to filter other Ctrl, Home, Del, and Enter events...)
Usage with jq :
<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>
Onkeyup attribute:
<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>
Yes, HTML5 does. Try this code (w3school):
<!DOCTYPE html>
<html>
<body>
<form action="">
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
<input type="submit" />
</form>
</body>
</html>
I finished using this function:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"
This works well in IE and Chrome, I don´t know why it´s not work well in firefox too, this function block the tab key in Firefox.
For the tab key works fine in firefox add this:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"
So simple....
// In a JavaScript function (can use HTML or PHP).
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
In your form input:
<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>
With input max. (These above allows for a 12-digit number)
This removes any bad character instantly, allows only one dot, is short, and allows backspace, etc.:
$('.numberInput').keyup(function () {
s=$(this).val();
if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});
My solution for a better user experience:
HTML
<input type="tel">
jQuery
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9','.']
return keys.indexOf(event.key) > -1
})
Details:
First of all, input types:
number
shows up/down arrows shrinking the actual input space, I find them ugly and are only useful if the number represents a quantity (things like phones, area codes, IDs... don't need them)
tel
provides similar browser validations of number without arrows
Using [number / tel] also helps showing numeric keyboard on mobile devices.
For the JS validation I ended up needing 2 functions, one for the normal user input (keypress) and the other for a copy+paste fix (change), other combinations would give me a terrible user experience.
I use the more reliable KeyboardEvent.key instead of the now deprecated KeyboardEvent.charCode
And depending of your browser support you can consider using Array.prototype.includes() instead of the poorly named Array.prototype.indexOf() (for true / false results)
Give the input field a class (<input class="digit" ...>
) and use jquery as below .
jQuery(document).ready(function () {
jQuery('input.digit').live('input keyup',function(e){ jQuery(this).val(jQuery(this).val().replace( /[^\d]/g ,'')); });
});
Above code also works to disable special characters in Ctrl+V
strokes and right click
strokes also.
JavaScript code:
function validate(evt)
{
if(evt.keyCode!=8)
{
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
}
HTML code:
<input type='text' name='price' value='0' onkeypress='validate(event)'/>
works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)
I was looking for a way to block an input of numbers, then, as I did not find it in answers, this code worked fine for me.
I just need to input it in the onkeypress event.
If you need just to block an input of numbers, I believe this will work fine.
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"
You can use pattern for this:
<input id="numbers" pattern="[0-9.]+" type="number">
Here you can see the complete mobile website interface tips.
A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.
This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.
The below script allows positive and negative numbers
1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed
var input = document.getElementById('number');_x000D_
input.onkeyup = input.onchange = enforceFloat;_x000D_
_x000D_
//enforce that only a float can be inputed_x000D_
function enforceFloat() {_x000D_
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;_x000D_
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;_x000D_
if (!valid.test(this.value)) {_x000D_
var n = this.value.match(number);_x000D_
this.value = n ? n[0] : '';_x000D_
}_x000D_
}
_x000D_
<input id="number" value="-3.1415" placeholder="Type a number" autofocus>
_x000D_
EDIT: I removed my old answer because I think it is antiquated now.
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
Use:
<script>
function onlyNumber(id){
var DataVal = document.getElementById(id).value;
document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
}
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">
And if you want to update a value after press key, you can change onChange for onKeypress, onKeyDown or onKeyup. But event onKeypress doesn't running in any browsers.
Here is a very short solution that doesn't use the deprecated keyCode
or which
, doesn't block any non input keys, and uses pure javascript. (Tested in Chromium 70.0.3533, Firefox 62.0, and Edge 42.17134.1.0)
HTML:
<input type="text" onkeypress="validate(event)">
JS:
function validate(ev) {
if (!ev) {
ev = window.event;
}
if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
return ev.preventDefault();
}
}
HTML5 supports regexes, so you could use this:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
Warning: Some browsers don't support this yet.
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).
Code bellow will also check for PASTE event.
Uncomment "ruleSetArr_4" and add(concate) to "ruleSetArr" to allow FLOAT numbers.
Easy copy/paste function. Call it with your input element in parameter.
Example: inputIntTypeOnly($('input[name="inputName"]'))
function inputIntTypeOnly(elm){_x000D_
elm.on("keydown",function(event){_x000D_
var e = event || window.event,_x000D_
key = e.keyCode || e.which,_x000D_
ruleSetArr_1 = [8,9,46], // backspace,tab,delete_x000D_
ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57], // top keyboard num keys_x000D_
ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys_x000D_
ruleSetArr_4 = [17,67,86], // Ctrl & V_x000D_
//ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values_x000D_
ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4); // merge arrays of keys_x000D_
_x000D_
if(ruleSetArr.indexOf() !== "undefined"){ // check if browser supports indexOf() : IE8 and earlier_x000D_
var retRes = ruleSetArr.indexOf(key);_x000D_
} else { _x000D_
var retRes = $.inArray(key,ruleSetArr);_x000D_
};_x000D_
if(retRes == -1){ // if returned key not found in array, return false_x000D_
return false;_x000D_
} else if(key == 67 || key == 86){ // account for paste events_x000D_
event.stopPropagation();_x000D_
};_x000D_
_x000D_
}).on('paste',function(event){_x000D_
var $thisObj = $(this),_x000D_
origVal = $thisObj.val(), // orig value_x000D_
newVal = event.originalEvent.clipboardData.getData('Text'); // paste clipboard value_x000D_
if(newVal.replace(/\D+/g, '') == ""){ // if paste value is not a number, insert orig value and ret false_x000D_
$thisObj.val(origVal);_x000D_
return false;_x000D_
} else {_x000D_
$thisObj.val(newVal.replace(/\D+/g, ''));_x000D_
return false;_x000D_
};_x000D_
_x000D_
});_x000D_
};_x000D_
_x000D_
var inptElm = $('input[name="inputName"]');_x000D_
_x000D_
inputIntTypeOnly(inptElm);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input type="text" name="inputName" value="1">
_x000D_
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
You can also compare input value (which is treated as string by default) to itself forced as numeric, like:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
However, you need to bind that to event like keyup etc.
I opted to use a combination of the two answers mentioned here i.e.
<input type="number" />
and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
<input type="text" onkeypress="return isNumberKey(event);">
Below function will check for every input char if it is number.
numeric: value => {
let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
console.log(numset.has(value.substring(value.length - 1, value.length)));
}
Thanks guys this really help me!
I found the perfert one really useful for database.
function numonly(root){
var reet = root.value;
var arr1=reet.length;
var ruut = reet.charAt(arr1-1);
if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
}
}
}
Then add the eventhandler:
onkeyup="numonly(this);"
2 solutions:
Use a form validator (for example with jQuery validation plugin)
Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("^\d*\.?\d*$");
if (!regExpr.test(field.value)) {
// Case of error
field.value = "";
}
}
</script>
<input type="text" ... onblur="testField(this);"/>
I use the jquery.inputmask.js library you can download from NuGet. More specifically I use jquery.inputmask.regex.extensions.js that comes with it.
I give the input element a class, in this case reg
:
<input type="number" id="WorkSrqNo" name="WorkSrqNo" maxlength="6" class="reg"/>
And then in JavaScript I set the mask:
var regexDigitsOnly = "^[0-9]*$";
$('input.reg').inputmask('Regex', { regex: regexDigitsOnly });
This is for digits only, but you can alter the regular expression to accept ".".
By using this it is impossible to enter characters that are not digits. It is useful to have these inputmask libraries for general formatting.
You can attach to the key down event and then filter keys according to what you need, for example:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
And the actual JavaScript handler would be:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.
Source: Stackoverflow.com