Input number validation - Restrict to enter only numbers or digits, int & float both

How to restrict the input field to enter only numbers/digits int and float both. Sometimes we need to allow both integer as well as float value for fields like amount, so in that case the validation is required. There are no of solutions available but they are of large size code. So need a short but effective code.

<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

Answers:

Answer

No need for the long code for number input restriction just try this code.

It also accepts valid int & float 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 are for most common use case - validating input as a number.

But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.

$(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 />

Answer

One-liner solution #1:

Use <input type="number"> with the step attribute.

<input type="number" step="0.0001"> // The user can enter up to 4 decimal places.

<input type="number" step="any"> // Not supported in all browsers, but permits numbers of any decimal precision.

You can also use the min and/or max attributes to set the minimum value and/or the maximum value.


One-liner solution #2:

Use a regular text input element with a RegExp pattern attribute.

<input type="text" pattern="^-?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)$">

This RegExp accepts numbers beginning with a dot ( . ) and/or a negative sign ( - ).

Answer

First things first. I prefer showing the invalid keystrokes rather than preventing them. User Experience Stack Exchange seems to agree at the moment (see this question).

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

Second. This doesn't replace a validation step. There are certain valid keystroke combinations that are not valid numbers, but need to be permitted in order to enter valid numbers. For example, the user could type a decimal mark (full stop or comma, depending on the language they are using), and then leave the text box, and you don't have a valid number. The following strings are all starts of numbers, but not yet valid:

  • .
  • -.
  • ,
  • -,

The first two are the start of .5 or -.5, while the last two are the same in the various languages that use a comma instead of a full stop for the decimal mark.

This brings us to the (already rejected)

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

Of course, you will have to include a JavaScript script to fix non-modern browsers, but those are available. In theory, these should also work correctly when the user works in a language that uses the comma instead of the full stop for the decimal mark. Even better, since users usually use only one browser, and since they will be used to how input number works in that browser, and since they will spend most of their time on other websites than yours, they may get confused if your website does not behave the same way they are used to.

But maybe you still want to make your own solution. If all else fails, I would go with a regular expression (yes, I know, I now have two problems). I don't believe in allowing spaces, so I limit it to a negative sign, digits, and one decimal mark (whichever they are using). 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">

This ALMOST works. The only problem I now have is, it assumes any character you type goes at the end of the string. This is fine except for the '-' for negative numbers, which is only allowed at the beginning. So you can type -5.4, but if you type 5.4 and then hit the home key or left arrow back to the beginning, it won't let you make it negative.

It also won't deal with pasting. Paste is a complicated topic. I don't agree with rejecting all paste operations. I feel the best option here is to just let the user paste and let the validator pick up any invalid numbers.

Answer

You can add a pattern attribute to the input field. If the input value doesn't match the pattern, you can style the input field and/or show an error message by using the css selector :invalid:

.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' makes mobile browsers open a number keyboard, but of course you can also set the type to text.
  • Browser support for the pattern input attribute: http://caniuse.com/#feat=input-pattern
  • Browser support for the :invalid css selector: http://caniuse.com/#feat=form-validation
  • The pattern regex doesn't support exponential notation, e.g. 1.23e4.
  • The pattern regex doesn't allow spaces – they are not valid in int and float notation, but allowing them might improve user experience.
Answer

Call one jquery function in onkeypress of the textbox. In that function use the respective ascii code to restrict input.

Answer

User can not enter Decimal value in js. Try using this code :

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.