Muhammed Athimannil Muhammed Athimannil - 2 months ago 17
Javascript Question

HTML5 input type=number should allow only unsigned integer

How to prevent other number related characters other than unsigned integer

For example

-
e
.
..etc

Demo: http://codepen.io/anon/pen/jrEGrK



<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<form action="#" class="container">
<br />
<br />
<br />
<input class="form-control" onkeyup="value=isNaN(parseFloat(value))?1000:value" type="number" value="0">
</form>




Answer

function validate(e) {
  var ev = e || window.event;
  var key = ev.keyCode || ev.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]/;
  if( !regex.test(key) ) {
    ev.returnValue = false;
    if(ev.preventDefault) ev.preventDefault();
  }
}
<input type='text' onkeypress='validate(event)' />

Comments