2

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>

4
  • 1
    Your question is not clear, please explain what you want to achieve, and add some code example in the question. Not just a link, please. Commented Sep 5, 2016 at 14:30
  • @Mario Alexandro Santini I need to type salary in this field. that means user shouldn't be able to type dot, comma, minus....etc Commented Sep 5, 2016 at 14:31
  • 2
    In addition to all the answers, don't forget to validate the format on the backend. You don't want your service to crash and be potentially exploitable. Commented Sep 5, 2016 at 14:35
  • 1
    @JoseGómez There is backend validation. it is just UX purpose Commented Sep 5, 2016 at 14:47

3 Answers 3

6

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

<input pattern="[1-9][0-9]*" ...>
Sign up to request clarification or add additional context in comments.

Comments

3

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

1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.