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)")
}
}
This question is related to
javascript
validation
numbers
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');" >
_x000D_
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)")
}
}
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.
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
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>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>_x000D_
<script type="text/babel">_x000D_
class Demo extends React.Component {_x000D_
state = {_x000D_
input: '',_x000D_
}_x000D_
_x000D_
onChange = e => {_x000D_
let input = e.target.value.replace(/[^0-9]/g, '');_x000D_
this.setState({ input });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<input_x000D_
value={this.state.input}_x000D_
placeholder="Enter a number"_x000D_
onChange={this.onChange}_x000D_
/>_x000D_
<br />_x000D_
<h1>{this.state.input}</h1>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Demo />, document.getElementById('root'));_x000D_
</script>
_x000D_
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
function validateNumber(e) {_x000D_
const pattern = /^[0-9]$/;_x000D_
_x000D_
return pattern.test(e.key )_x000D_
}
_x000D_
_x000D_
<input name="username" id="username" onkeypress="return validateNumber(event)">
_x000D_
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
onload =function(){ _x000D_
var ele = document.querySelectorAll('.number-only')[0];_x000D_
ele.onkeypress = function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))_x000D_
return false;_x000D_
}_x000D_
ele.onpaste = function(e){_x000D_
e.preventDefault();_x000D_
}_x000D_
}
_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
$(function(){_x000D_
_x000D_
$('.number-only').keypress(function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
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(){_x000D_
_x000D_
$('.number-only').keyup(function(e) {_x000D_
if(this.value!='-')_x000D_
while(isNaN(this.value))_x000D_
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')_x000D_
.split('').reverse().join('');_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
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!");
};
};
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();
}
});
}
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
// 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();
}
}
});
});
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.
Source: Stackoverflow.com