How to prevent other number related characters other than unsigned integer
For example -
e
.
..etc
Demo:
<link href=".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>
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./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>
Share
Improve this question
edited Sep 5, 2016 at 14:32
Mo.
asked Sep 5, 2016 at 14:25
Mo.Mo.
27.5k36 gold badges166 silver badges232 bronze badges
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. – Mario Santini 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, ma, minus....etc – Mo. 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. – Jose Gómez Commented Sep 5, 2016 at 14:35
-
1
@JoseGómez There is backend validation. it is just
UX
purpose – Mo. Commented Sep 5, 2016 at 14:47
3 Answers
Reset to default 6If you're ok with HTML5 why not use the pattern attribute and define a number only regex?
<input pattern="[1-9][0-9]*" ...>
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)' />
Taking a clue from your implementation, what if you use a regular expression like that:
onkeyup="value=/^\d+$/.test(value)?value:1000"