Mo.
Mo.

Reputation: 27513

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>

Upvotes: 2

Views: 3361

Answers (3)

redneb
redneb

Reputation: 23920

Taking a clue from your implementation, what if you use a regular expression like that:

onkeyup="value=/^\d+$/.test(value)?value:1000"

Upvotes: 1

Vladu Ionut
Vladu Ionut

Reputation: 8193

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

Upvotes: 3

If you're ok with HTML5 why not use the pattern attribute and define a number only regex?

<input pattern="[1-9][0-9]*" ...>

Upvotes: 6

Related Questions