How can I not allow numbers in a textbox?

11

Well folks, I'm trying to validate but have not yet succeeded. I want to do a function that does not let me enter numbers in a textbox .

Here's an example of how I do it today.

 $(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");
        }
    });
});
    
asked by anonymous 05.01.2016 / 00:36

6 answers

23

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 verifies 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><textareaid="nome_contacto" ></textarea>

But if you really want to block incoming numbers you can check the keyCode . The full list of these is here .

The keyCodes numbers go 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><textareaid="nome_contacto"></textarea>

I used the .preventDefault() method to block the entry.

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><textareaid="nome_contacto"></textarea>

In this case, you just need to deny the condition of the previous option.

    
05.01.2016 / 00:53
10

An alternative to the solutions presented is to block only the submission of the form with attributes HTML5 validation , not the user input.

In fact, there is no way to ensure that the data entered is in accordance with what is planned, if the user wants to make a noise, he will do so. If you have Javascript disabled in the browser and you have a validation through script, it would pass smoothly. If he wants to inspect the source code of the page and modify some attribute in the HTML or a function in a JS file that deals with the validation, it would also pass a good one.

That's why there should be other checks on the server, this subject has already generated a question about validation efficiency only in < in> client-side . Validation in the client is only an attempt to save resources and avoid performing requests at random to the server.

Returning to the validation attributes, one of the main advantages is to eliminate the need to use Javascript to validate fields. On the other hand, there is the good bad old story of limited support in some browsers, so my answer may not be the best solution depending on the users who access (or can access) your page.

1st solution: type='text' with attribute pattern

One way is to set the attribute pattern field to accept only numbers.

<input type='text' pattern='\d*'/>

Example online .

2nd solution: Use a field of type number

Semantically, this would be the best option to create a field that only accepts numbers, no doubt. But here comes the compatibility issue and support for the type='number' fields sucks .

<input type='number'/>

Online sample .

You can even use the :invalid > to inform the user what type of data is expected in that field:

p {
  color: #ea6153;
  display: none
}

input:invalid + p {
  display: inline
}
<input type='text' pattern='\d*'/>
<p>Ei! Este campo só pode ter números.</p>


Completing

Validations with HTML is something recent, this explains the limited support in some browsers. But I look forward to the implementations of this feature since joining the specification . , we just need to give it some more time.

In the same way that we had to use Javascript in the past to make animations, however simple - today we do it elegantly with CSS3 only - we will soon be using HTML only to limit the entries in one field.

Can I Use? is a great site to track the compatibility of a feature . There are libraries like Modernizr that are there to detect these features and help the developer make use of

    
15.01.2016 / 10:45
4

Just one alternative, complementing Samir Braga's response.

Example to only allow numbers in a text input without the use of jQuery:

document.getElementById("nome_contato").onkeypress = function(event) {
    var keyCode = (event.keyCode ? event.keyCode : event.which);
    if (!(keyCode > 47 && keyCode < 58)) {
        event.preventDefault();
    }
};
    
05.01.2016 / 12:43
2

I made a simple code. See if it helps.

document.getElementById('texto').addEventListener( 'keyup', function() {

    this.value = this.value.replace( /[0-9]*/g, '' );

});
<input type="text" id="texto" />
    
18.01.2016 / 19:06
1

A simple way to solve this is as follows:

function isNumber(el) {
    var reg = /[0-9]+/; 
    if ( reg.exec(el) ) {
        return true;
    }
   return false;
}

$(document).ready(function () {
    $('#nome_contacto').on('change', function() {
        var textoValida = $('#nome_contacto').val();
         if (isNumber(textoValida)) {
            alert("Só utilize letras!");
            return false;
         }
    });
});

But if you just want to lock the field, simply do a replace with keyup or keypress :

$(function() {
    $('#nome_contacto').on('keypress', function() {
        $(this).val($(this).val().replace(/[0-9]+/g,''))
    });
});

input:

<input type="text" id="nome_contacto">

There are also ways to use the HTML5 pattern attribute:

<input type="text" required="required" name="text" pattern="[^0-9]+$" />
    
19.01.2016 / 04:46
0

I often use Jquery Mask ( link )

Then I create the rules with regular expression ex:

$('.soNumeros').mask('########', {
            'translation': {
                #: { pattern: /[0-9]/ },
            }
        });
    
15.01.2016 / 16:40