Checking the amount of input data - Restriction on entering only numbers or digits, int & float as

How to limit the input field to enter only numbers / digits int and swim like. Sometimes we need to allow both an integer and a float for fields such as quantity, so a check is required in this case. There are no solutions available, but they have a large code size. Therefore, you need a short but effective code.

<p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 
+8
javascript jquery floating-point validation numbers
source share
6 answers

There is no need for a long code to restrict number entry, just try this code.

It also takes valid int and float values ​​for both values.

Javascript Approach

 onload =function(){ var ele = document.querySelectorAll('.number-only')[0]; ele.onkeypress = function(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false; } ele.onpaste = function(e){ e.preventDefault(); } } 
 <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 

JQuery approach

 $(function(){ $('.number-only').keypress(function(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false; }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 

UPDATE

The above answers relate to the most commonly used use case - checking input as a number.

But according to the comments, some want to allow several special cases, for example, negative numbers and showing invalid keystrokes before deleting it, so the code snippet for such special cases is given below.

 $(function(){ $('.number-only').keyup(function(e) { if(this.value!='-') while(isNaN(this.value)) this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'') .split('').reverse().join(''); }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 
+15
source share

You said you need a "short but effective code." This code works, and this is just one line!

HTML5 has a function for that! The HTML input tag supports the type="number" attribute. To enable decimal places, add the attribute value step="0.0001" to the tag.

 <input type="number" step="0.0001"> 

You can also use the min and max attributes to set the minimum value or maximum value. step="0.0001" may be even smaller, for example, 0.000001 , but 0.0001 should be good enough.

JavaScript, jQuery UI also has an exact widget matching what you want: jQuery UI Spinner , plus zoom buttons.


Edit: step="any" now supported in Firefox, which allows you to enter as many decimal places as possible.

+9
source share

First of all. I prefer to show invalid keystrokes rather than prevent them. The Stack Exchange user stack seems to agree at the moment ( see this question ).

However, not everyone agrees, so let's see what we can do.

Secondly. This does not replace the verification step. There are certain valid key combinations that are not valid numbers, but must be allowed to enter valid numbers. For example, a user can enter a decimal place (a full stop or a comma, depending on the language they use), and then leave a text field and you do not have a real number. The following lines are all number starts, but not yet valid:

  • .
  • -.
  • -

The first two are the start of .5 or -.5, while the last two are the same in different languages, which use a comma instead of stopping completely for the decimal place.

This leads us to (already rejected)

 <input type="number" step="any"> 

Of course, you will have to enable a JavaScript script to fix non-modern browsers, but they are available. Theoretically, they should also work correctly when the user works in a language that uses a comma instead of a full stop for the decimal mark. Even better, since users usually use only one browser, and since they will be used to enter the login number in this browser, and since they will spend most of their time on sites other than yours, they can get confused if your site does not behave just like they used to.

But maybe you still want to create your own solution. If everything else fails, I would go with a regex (yes, I know, I now have two problems). I do not believe in resolving spaces, so I limit it to a negative sign, numbers, and one decimal place (depending on what they use). For example:

 $('.rational-number').on('keypress', function(e) { if (e.charCode >= 32 && e.charCode < 127 && !/^-?\d*[.,]?\d*$/.test(this.value + '' + String.fromCharCode(e.charCode))) { return false; } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type-"text" class="rational-number"> 

It ALMOST works. The only problem I am facing right now is assuming that any character you enter goes at the end of the line. This is normal, with the exception of '-' for negative numbers, which is allowed only at the beginning. Thus, you can enter -5.4, but if you type 5.4 and then delete the home key or left arrow before the start, this will not allow you to make it negative.

He will also not engage in insertion. Paste is a complicated topic. I do not agree with the rejection of all operations with the paste. I believe that the best option is to simply let the user insert and let the validator pick up any invalid numbers.

+4
source share

You can add the pattern attribute to the input field. If the input value does not match the pattern, you can create an input field and / or display an error message using the css :invalid selector:

 .error-msg { display: none; /* Hide by default */ } .number-only:invalid { background: pink; } .number-only:invalid + .error-msg { display: inline; } 
 <input type='tel' class='number-only' pattern='[+\-]?\d*\.?\d+' /> <span class='error-msg'>Please enter a valid integer or float value.</span> 

Some notes:

  • type='tel' allows mobile browsers to open the numeric keypad, but of course you can also set the type to text .
  • Browser support for the input attribute pattern : http://caniuse.com/#feat=input-pattern
  • Browser support for selector :invalid css: http://caniuse.com/#feat=form-validation
  • A regular expression pattern does not support exponential notation, for example. 1.23e4 .
  • The regular expression of the template does not allow spaces - they are not valid in the notation int and float, but allow them to improve the user experience.
+3
source share

Call one jquery function in the onkeypress text field. In this function, use the appropriate ascii code to restrict input.

+1
source share

User cannot enter decimal value in js. Try using this code:

 if(document.getElementById(id).value.indexOf('.') != -1){ print "do not Enter decimal nuber"; } 
-4
source share

All Articles