Question:
Hi guys, I'm trying to do a validation but I still haven't been successful. I want to make a function that doesn't let me enter numbers in a textbox
.
Here's an example of how I currently do it.
$(document).ready(function () {
$('#nome_contacto').change(function validar() {
var textoValida = $('#nome_contacto').val();
if (textoValida == "1" || textoValida == "2" || textoValida == "3" || textoValida == "4" || textoValida == "5" || textoValida == "6" || textoValida == "7" || textoValida == "8" || textoValida == "9") {
window.alert("Só letras");
}
});
});
Answer:
You can do this using a Regular Expression. Look:
$('#nome_contacto').on('input', function(e) {
if(/[0-9]/g.test(this.value)){
alert("Apenas letras");
}
});
In this case, the expression was /[0-9]/g
which checks for the existence of numbers, which can be replaced by \d
.
test here
$('#nome_contacto').on('input', function() {
if (/[0-9]/g.test(this.value)) {
alert("Apenas letras");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="nome_contacto" ></textarea>
But if you really want to block numbers from entering you can check the keyCode
. The complete list of these is here .
The keyCodes
of the numbers range from 48 to 57, so I checked 47 > keyCode < 57
.
$('#nome_contacto').keypress(function(e) {
var keyCode = (e.keyCode ? e.keyCode : e.which); // Variar a chamada do keyCode de acordo com o ambiente.
if (keyCode > 47 && keyCode < 58) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="nome_contacto"></textarea>
I used the .preventDefault()
method to block the input.
Here's an alternative if you just want numbers…
Due to the ambiguity of the question, I made this option:
$('#nome_contacto').keypress(function(e) {
var keyCode = (e.keyCode ? e.keyCode : e.which);
if (!(keyCode > 47 && keyCode < 58)) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="nome_contacto"></textarea>
In this case, just deny the condition of the previous option.