Only number input in php

I need to make sure that a certain field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.

Is there a neat way to achieve this?

asked Dec 19, 2012 at 12:40

chtenbchtenb

13.9k12 gold badges73 silver badges112 bronze badges

3

HTML 5

You can use HTML5 input type number to restrict only number entries:


This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

See also //github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text , including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purpose, you can have JS validation as below:

function isNumberKey[evt]{
    var charCode = [evt.which] ? evt.which : evt.keyCode
    if [charCode > 31 && [charCode < 48 || charCode > 57]]
        return false;
    return true;
}


If you want to allow decimals replace the "if condition" with this:

if [charCode > 31 && [charCode != 46 &&[charCode < 48 || charCode > 57]]]

Source: HTML text input allow only numeric input

JSFiddle demo: //jsfiddle.net/viralpatel/nSjy7/

answered Dec 19, 2012 at 12:42

Viral PatelViral Patel

8,3063 gold badges31 silver badges29 bronze badges

15

You can also use the pattern attribute in html5:

 

Input validation tutorial

Although, if your doctype isn't html then I think you'll need to use some javascript/jquery.

answered Dec 19, 2012 at 12:45

martincarlin87martincarlin87

10.5k24 gold badges97 silver badges144 bronze badges

6

Quick and Easy Code


This will permit usage of numbers and backspace only.

If you need decimal part too, use this code fragment


answered Dec 16, 2018 at 14:48

2

Please try this code along with the input field itself

it will work fine.

answered Aug 23, 2017 at 11:12

subindas pmsubindas pm

2,46423 silver badges18 bronze badges

1

You can use following one line code as :


It will accept numbers ony.

answered Aug 27, 2021 at 8:58

w.Dayaw.Daya

3541 gold badge5 silver badges11 bronze badges

2

You can use an . This will only allow numbers to be entered into othe input box.

Example: //jsfiddle.net/SPqY3/

Please note that the input type="number" tag is only supported in newer browsers.

For firefox, you can validate the input by using javascript:

//jsfiddle.net/VmtF5/

Update 2018-03-12: Browser support is much better now it's supported by the following:

answered Dec 19, 2012 at 12:45

6


and in the js:

function isNumber[e]{
    e = e || window.event;
    var charCode = e.which ? e.which : e.keyCode;
    return /\d/.test[String.fromCharCode[charCode]];
}

or you can write it in a complicated bu useful way:


Note:cross-browser and regex in literal.

answered Feb 8, 2014 at 9:13

Fredrick GaussFredrick Gauss

5,0871 gold badge26 silver badges43 bronze badges

3

You can use the tag with attribute type='number'.

For example you can use

This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

answered May 15, 2017 at 7:19

I have used regular expression to replace the input value with the pattern needed.

var userName = document.querySelector['#numberField'];

userName.addEventListener['input', restrictNumber];
function restrictNumber [e] {  
  var newValue = this.value.replace[new RegExp[/[^\d]/,'ig'], ""];
  this.value = newValue;
}
  

answered Aug 26, 2018 at 10:27

1

function AllowOnlyNumbers[e] {

e = [e] ? e : window.event;
var clipboardData = e.clipboardData ? e.clipboardData : window.clipboardData;
var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
var str = [e.type && e.type == "paste"] ? clipboardData.getData['Text'] : String.fromCharCode[key];

return [/^\d+$/.test[str]];
}

Integer Textbox

JSFiddle: //jsfiddle.net/ug8pvysc/

answered Nov 19, 2015 at 8:04

2


onkeyup triggers when the key is released.

isNaN[parseFloat[value]]? checks if the input value is not a number.

If it is not a number the value is set to 1000 : If it is a number the value is set to the value.

note: For some reason it only works with type="number"

To make it even more exiting, you can also have a boundary:


Enjoy!

answered Nov 28, 2015 at 21:41

user40521user40521

1,85919 silver badges7 bronze badges

I fought with this one for a bit. Many solutions here and elsewhere seemed complicated. This solution uses jQuery/javascript alongside HTML.

    

    $[document].on['change', '.validateNumber', function[] { 
        var abc = parseInt[$[this].val[]];
        if[isNaN[abc]] { abc = 1; }
        $[this].val[abc];
    }];

In my case I was tracking small quantities with a minimum value of 1, hence the min="1" in the input tag and abc = 1 in the isNaN[] check. For positive only numbers you could change those values to 0 and even simply remove the min="1" from the input tag to allow for negative numbers.

Also this works for multiple boxes [and could save you some load time over doing them individually by id], just add the "validateNumber" class where needed.

Explanation

parseInt[] basically does what you need, except that it returns NaN rather than some integer value. With a simple if[] you can set the "fallback" value that you prefer in all the cases NaN is returned :-]. Also W3 states here that the global version of NaN will type cast before checking which gives some extra proofing [Number.isNaN[] does not do that]. Any values sent to a server/backend should still be validated there!

answered Jun 23, 2016 at 22:44

IsaiahIsaiah

4645 silver badges16 bronze badges

Simple enough?

inputField.addEventListener['input', function [] {
  if [[inputField.value/inputField.value] !== 1] {
    console.log["Please enter a number"];
  }
}];

answered Apr 8, 2020 at 2:47

NormajeanNormajean

9473 gold badges10 silver badges21 bronze badges

1

I use this for Zip Codes, quick and easy.


answered Oct 14, 2013 at 19:56

Justin BuserJustin Buser

2,79524 silver badges32 bronze badges

if you can use HTML5 you can do If not you will have to either do it through javascript as you said it doesnt get submited to do it from codebehind.



function validate[]{
  var returnString;
  var text = document.getElementByID['numbersOnly'].value;
  var regex = /[0-9]|\./;
  var anArray = text.split[''];
  for[var i=0; i 57]]
        return false;
    return true;
}

It's good but not perfect. It works out for me, but i get a warning that the if-statement can be simplified.

Then it looks like this, which is way prettier:

function isNumberKey[evt]{
    var charCode = [evt.which] ? evt.which : event.keyCode;
    return ![charCode > 31 && [charCode < 48 || charCode > 57]];
}

Would comment the original post, but my reputation is too low to do so [just created this account].

answered Feb 14, 2017 at 12:58

Chris H.Chris H.

1171 silver badge3 bronze badges

Add inside your input tag: onkeyup="value=value.replace[/[^\d]/g,'']"

answered Jul 5, 2018 at 4:25

1

if not integer set 0



$['#min-value'].change[function []
            {   
                var checkvalue = $['#min-value'].val[];
                if [checkvalue != parseInt[checkvalue]]
                    $['#min-value'].val[0];
            }];

answered Dec 12, 2014 at 10:50

webskywebsky

2,9421 gold badge33 silver badges29 bronze badges

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:




    Input Key Filter Test
	
	
	
	
	
	
			
	
	
	


	

Integer field

CreateIntFilter["Integer", function[event]{//onChange event inputKeyFilter.RemoveMyTooltip[]; var elementNewInteger = document.getElementById["NewInteger"]; var integer = parseInt[this.value]; if[inputKeyFilter.isNaN[integer, this]]{ elementNewInteger.innerHTML = ""; return; } //elementNewInteger.innerText = integer;//Uncompatible with FireFox elementNewInteger.innerHTML = integer; } //onblur event. Use this function if you want set focus to the input element again if input value is NaN. [empty or invalid] , function[event]{ inputKeyFilter.isNaN[parseInt[this.value], this]; } ]; New integer:

Also see my page "Integer field:" of the example of the input key filter

answered Jul 31, 2015 at 2:37

AndrejAndrej

6294 silver badges12 bronze badges

I updated some answers posted to add the following:

Suraj Rao

29.1k11 gold badges95 silver badges100 bronze badges

answered Oct 17, 2018 at 12:08

When using this code you cant use "BackSpace Button" in Mozilla Firefox you can only use backspace in Chrome 47 && event.charCode < 58;" pattern="[0-9]{5}" required>

answered May 25, 2015 at 3:36

For general purpose, you can have JS validation as below:

It will work for Numeric keypad and normal number key's

function isNumberKey[evt]{
        var charCode = [evt.which] ? evt.which : event.keyCode

if [charCode < 31 || [charCode >= 48 && charCode = 96 && charCode 
 
 = 48 && ASCIICode = 96 && ASCIICode 

Chủ Đề