44

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?

Part of the Login

<form name="myForm">
    <label for="firstname">Age: </label>
    <input name="num" type="text" id="username" size="1">
    <input type="submit" value="Login" onclick="return validateForm()">

function validateForm()
{

    var z = document.forms["myForm"]["num"].value;
    if(!z.match(/^\d+/))
        {
        alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
        }
}
2
  • 3
    You are better to use test, which returns a boolean: if (/\D/.test(z)) {/* non-digit found */}.
    – RobG
    May 23, 2012 at 6:49
  • Also better to put the listener on the form as it can be submitted without pressing the submit button.
    – RobG
    Dec 10, 2014 at 21:10

15 Answers 15

43

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.

Edit:

RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

Simply omit the negating ! and use if(/\D/.test(z)).

5
  • 1
    this doesn't work. Now it just accepts the validation even if its not digits. i changed it to : if(!z.match(/^\d+$/.$))
    – Anthony Do
    May 23, 2012 at 5:15
  • Wait, are you not getting z.match(/^\d+$/) to work? It works fine for me. The final .$ in the code from your comment does nothing -- that period and dollar sign are outside the regex pattern and are interpreted as regex modifier characters (like g for global or i for case-insensitive).
    – apsillers
    May 23, 2012 at 5:22
  • 10
    @apsillers—consider instead /\D/.test(z), shorter and simpler.
    – RobG
    May 23, 2012 at 6:51
  • You don't need a ! if using /\d/.test(z)
    – JillAndMe
    Nov 20, 2018 at 5:06
  • @JillAndMr That tests for the presence of any numbers, but the question asks to test if a string is only numbers. (For example, your test would matchhello5 but that is not a numbers-only string.)
    – apsillers
    Nov 20, 2018 at 12:52
27

here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313

<input type="text" 
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>

and this will not accept entering the dot (.), so it will only accept integers

<input type="text" 
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>

this way you will not permit the user to input anything but numbers

2
  • on pasting text this is not validating Jan 28, 2016 at 10:49
  • You can validate on another even such submitting form Dec 8, 2016 at 3:51
17

This one worked for me :

function validateForm(){

  var z = document.forms["myForm"]["num"].value;

  if(!/^[0-9]+$/.test(z)){
    alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
  }

}
8

Late answer,but may be this will help someone

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Use will be like

nn=document.forms["myForm"]["num"].value;

ans=isNumber(nn);

if(ans)
{
    //only numbers
}

This ans was found from here with huge vote

Validate numbers in JavaScript - IsNumeric()

8

function validateNumber(e) {
            const pattern = /^[0-9]$/;

            return pattern.test(e.key )
        }
 
 <input name="username" id="username" onkeypress="return validateNumber(event)">

This approach doesn't lock numlock numbers, arrows, home, end buttons and etc

4

The simplest solution.

Thanks to my partner that gave me this answer.

You can set an onkeypress event on the input textbox like this:

onkeypress="validate(event)"

and then use regular expressions like this:

function validate(evt){
     evt.value = evt.value.replace(/[^0-9]/g,"");
}

It will scan and remove any letter or sign different from number in the field.

2
  • Does that still work when text is pasted in to an input textbox?
    – Joel B
    May 12, 2016 at 15:00
  • 1
    .replace(/[^0-9]/g,"") is the best and simplest solution I've found. I needed even commas and currency dot so .replace(/[^0-9,.]/g,"") was an exact match for me.
    – Shahar G.
    Jun 13, 2016 at 9:02
3

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

The above answers are for most common use case - validating input as a number.

But 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 />

2
  • 1
    Hey @vinayakj i have taken the reference of this answer for StackOverflow in spanish, btw excellent answer! es.stackoverflow.com/a/34744/95
    – Jorgesys
    Nov 19, 2016 at 1:34
  • 1
    Thanks @Elenasys.. sure.. thanks for spreading the answer to spanish audience.
    – vinayakj
    Nov 19, 2016 at 16:45
2

Using the form you already have:

var input = document.querySelector('form[name=myForm] #username');

input.onkeyup = function() {
    var patterns = /[^0-9]/g;
    var caretPos = this.selectionStart;

    this.value = input.value.replace(patterns, '');
    this.setSelectionRange(caretPos, caretPos);
}

This will delete all non-digits after the key is released.

2

Regular expressions are great, but why not just make sure it's a number before trying to do something with it?

function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
    if(Number(sum)) {
        alert(sum);
        } else {
            alert("Numbers only, please!");
        };
    };
1
  • this requires more computation than regex.
    – TV Nath
    Sep 23, 2014 at 4:42
2
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57)) 
{
   event.returnValue = false;
}
}

this function will allow only numbers in the textfield.

1
  • but cannot enter decimal using this!
    – vibs2006
    May 3, 2017 at 6:34
2
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}
2

I think we do not accept long structure programming we will add everytime shot code see below answer.

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

1

If you are using React, just do:

<input
  value={this.state.input}
  placeholder="Enter a number"
  onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
    state = {
      input: '',
    }
    
    onChange = e => {
      let input = e.target.value.replace(/[^0-9]/g, '');
      this.setState({ input });
    }
    
    render() {
        return (
          <div>
            <input
              value={this.state.input}
              placeholder="Enter a number"
              onChange={this.onChange}
            />
            <br />
            <h1>{this.state.input}</h1>
           </div>
        );
    }
}

ReactDOM.render(<Demo />, document.getElementById('root'));
</script>

1
  • 1
    Would have been great if I can use it for decimals too. Not allowing me to add "."
    – Tmh
    Sep 2, 2020 at 11:42
0

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

$(document).ready(function () {
       $(".nosonly").keydown(function (event) {
           // Allow only backspace and delete
           if (event.keyCode == 46 || event.keyCode == 8) {
               // let it happen, don't do anything
           }
           else {
               // Ensure that it is a number and stop the keypress
               if (event.keyCode < 48 || event.keyCode > 57) {
              alert("Only Numbers Allowed"),event.preventDefault();
               }
           }
       });
   });
0
0

Avoid symbols like "." "," "+" "-". I tried it and it works fine.

$('#example').keypress(function (evt) {            
  if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
    evt.preventDefault();
    evt.stopImmediatePropagation();
    return false;
  }      
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 19, 2022 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.