How can we not allow numbers in a textbox?

Asked

Viewed 3,120 times

11

Good people, I’m trying to do a validation but I haven’t succeeded yet. I want to do a function that won’t let me enter numbers into a textbox.

Follow an example of how I currently do.

 $(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");
        }
    });
});

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 checking the existence of numbers, which may 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 the input of numbers you can check the keyCode. The complete list of these is here.

The keyCodes of the numbers range from 48 to 57, so I did the check 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 method .preventDefault() to block the entrance.

Here’s an alternative to just in case you want numbers...

Because of the ambiguity of the question, I made that choice:

$('#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 case just deny the condition of the previous option.

  • Thank you. I’m editing with a way to really block the entrance, that’s what it refers to?

  • He only wants numbers, and he’s not allowing numbers. I just put one !in front of the expression !/[0-9]/g and I guess that’s right....

  • Ah, I don’t know where I was in the head rsrsrs. You’re right. But in case you just change the text of Alert, the rest is in agreement. In the question there is statement within Alert, "Letters only".. And I edited the answer. Take a look.

  • @Samirbraga thank you very much, my goal is to even block the entrance, the Alert is only for testing

  • 1

    @luisfigueiredo, if it has served perfectly. you can "accept" the answer, so the problem will be taken as solved.

  • thank you very much, it was very helpful

  • 1

    This is confused: "I want to do a function that doesn’t let me enter numbers into a textbox." The title says it’s just number, the body says it’s not for by number.

  • Samir, is what @Bacco is saying, according to the question is the opposite!

  • I understand @gustavox, I did according to the body. In itself alert() has "Only lestras". I had understood that the author wanted so, "my goal is to even block the entry, the Alert is only for testing"...

  • And I went now to look at my edition in the question, and it’s really confusing, because in the title I edited was "Bootstrap Cancel the insertion of numbers in textbox ", and I changed because in the question was " I want to make a function that nay let me enter numbers "but at the moment I didn’t even realize the contradiction...

  • Yes Samir, I only touched myself because I edited the question, but now I don’t even know what the AP wants anymore, it would be interesting for him to clarify better. @luisfigueiredo

  • I added an option according to the title. Anyway, it’s there..

  • Very good Samir, and for not being able to give you +1 again, hold there my congratulations on the full answer. : -) By the way, I don’t even know if my edition in the title is correct, or if the body of the text is incorrect. I hope that the AP goes back to the site and clarify... and that marks the answer as accepted, obv.

  • Thanks.. @gustavox, I wanted to get it over with rsrs... I hope he really comes back to edit the question as he wishes and free of ambiguities this time...rs

Show 9 more comments

10

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

In fact, there is no way to guarantee that the entered data is in accordance with the forecast, if the user wants to mess up he will do it. If you have Javascript disabled in your browser and you have a script validation, it would go smoothly. If he wants to inspect the source code of the page and modify some attribute in HTML or a function in a JS file dealing with validation, he would also pass a good.

That’s why on the server there must be other checks, this subject has generated up to a question about validation efficiency only in the client-side. The validation in client is only an attempt to save resources and avoid making random requests 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 and 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.

first solution: type='text' attribute-ridden pattern

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

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

Online example.


Solution 2: Use a field of the type number

Semantically, this would be the best option to create a field that accepts only numbers, no doubt. However, again comes the question of compatibility and the support to the fields type='number' is terrible.

<input type='number'/>

Online example.


You can even use the selector :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>


Concluding

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

In the same way that we used to use Javascript in the old days to make animations, no matter how simple they were - Today we do this elegantly only with CSS3 - soon we will be using HTML only to limit entries in a field.

The Can I Use? is a great site to track the compatibility of a Feature. There are libraries like the Modernizr that are there to detect these Features and help the developer make use of polyfill or what already exists natively.

4

Only one alternative, complementing Samir Braga’s response.

Example to allow only numbers in a text input without using jQuery:

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

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" />

1

A simple way to solve this is like this:

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, just 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 using the attribute Pattern HTML5:

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

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.