How to validate a numerical type field so that it does not accept the minus sign (-) or the plus sign (+). because it only accepts numbers but between numbers it also accepts + and less
How to validate a numerical type field so that it does not accept the minus sign (-) or the plus sign (+). because it only accepts numbers but between numbers it also accepts + and less
You can validate using Javascript that only accepts numerical values:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
I add a demo:
function validaNumericos(event) {
if(event.charCode >= 48 && event.charCode <= 57){
return true;
}
return false;
}
<input type="text" onkeypress='return validaNumericos(event)'/>
We have the case in which a user can paste text and not just enter it, therefore we have to be prepared for that and not allow entering or pasting text that is not numeric:
function validaNumericos(){
var inputtxt = document.getElementById('text');
var valor = inputtxt.value;
for(i=0;i<valor.length;i++){
var code=valor.charCodeAt(i);
if(code<=48 || code>=57){
inputtxt.value="";
return;
}
}
}
<input type="text" id="text" onblur="validaNumericos();" />
onload = function(){
var ele = document.querySelectorAll('.validanumericos')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<input class="validanumericos" type=text />
Another version but now using JQuery
$(function(){
$('.validanumericos').keypress(function(e) {
if(isNaN(this.value + String.fromCharCode(e.charCode)))
return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="validanumericos" type=text />
There is a response from @vinayakj with other options on the site in English. p>
To validate the type of field is number and the minimum is negative.
<input type="number" min="0" step="1"/>
You need a regular expression to validate only numbers something like [0-9]
, the following validates a 10 digit number but the last validation must be in server side language.
<input type="text" pattern="[0-9]{10}" />
If you want to use JavaScript then DO NOT USE JQUERY if your project is not using the library for anything else. Simple tasks are solved without loading a huge library for it.
Basically you need to add a function by pressing a key, by submitting a form or by clicking the submit:
<input type="text" onkeypress="validar_campo()">
<input type="submit" value="Login" onsubmit="return validar_campo()">
Now the function;
function validar_campo(evento){
evento.value = evento.value.replace(/[^0-9]/g,"");
}
Something simpler on the same line ( @Max response ):
<input type="text" onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;" />