How to check if there are numbers inside an input with Javascript?

Asked

Viewed 3,980 times

8

Form validation with Javascript is something routine in web development, but always cause headaches! My situation is as follows: I cannot allow numbers to enter a 'name' field, but how can I do this?

  • if any of the answers answered your question, mark as solved sff

7 answers

9

I recommend the use of the property Pattern from HTML5 for a type check, as it is not necessary to use Javascript.

In this case, your html would be the following:

<input type=nome pattern="[^0-9]+"/>

Explanation:

"[^0-9]+" would be a Regular Expression(Regex) stating that the user cannot enter numbers from 0 to 9(that is all), and the + informs that it has no character limit, you can put a limit by replacing the + for {50} for example there would be a limit of 50 characters.

Compatibility:

The Pattern property is present in all browsers that support HTML5.

Example running on Jsfiddle

  • 2

    +1 for presenting a simpler solution and without the need for javascript, in addition to teaching a new functionality that I did not know. :)

  • Only one addendum: it DOES NOT want to allow numbers in name fields, so the correct Pattern would be \w+.

  • 2

    the ^ denies all expression my dear, so 0-9 is being denied, ie, is worth anything but numbers 0-9, ie DOES NOT ALLOW numbers.

7

The best you can do is get a regular expression and compare the input with the expression.

Regular expression:

var verifyInt = /\d+/g;

And now you take the input and you use the match if the input contains the characters defined in verfyInt equaling the null:

if ($("#idInputNome").val().match(verifyInt) != null) {
    alert("A input Nome contém caracteres numéricos!");
}

EDIT: Follow the fiddle:

Fiddle

Fiddle with validation to submit form:

Fiddle with Submit form

  • 1

    The question of the OP is as follows "Como verificar se existem números dentro de um input em Javascript" until then your answer is right, but the OP also says: Não posso permitir a entrada de números em um campo do tipo 'nome', mas como posso fazer isso? then he’d be talking about my answer.

  • To solve this, what I did was: - Put a global variable that represented the errors to true; - Before doing Submit I checked the value of that same variable, if it were false did Submit; Your answer works perfectly, you only have the problem that there are users with outdated browser and do not support HTML5

1

This way here I’ve used and tested and it’s cool.

$('#id_do_seu_campo_input').bind('keyup', function() { 
    $(this).val( $(this).val().replace(/[^a-z]/g,'') ); 
});

hug.

  • The problem with this solution is that the cursor will be moved to the last position when the field value is changed with jQuery.fn.val for the new value.

1

You can use this way too.

$(document).ready(function(){
    $("#idInputNome").keypress(function (e) {
        var valor = String.fromCharCode(e.which);
        return !$.isNumeric(valor) ||
            (e.keyCode == 46 || e.keyCode == 9 ||
            e.keyCode == 8 || e.keyCode == 37 || e.keyCode == 39);
    });
});

1

2 modes.

first mode create through an input mask

<script src="jquery.js" type="text/javascript"></script>
<script src="https://raw.github.com/digitalBush/jquery.maskedinput/1.3.1/dist/jquery.maskedinput.js" type="text/javascript"></script>

And then would put only to accept ex characters:

jQuery(function($){
 $.mask.definitions['h'] = "[A-Za-z]";
  $("#ID_SeuCampo").mask("#hhhhhh");
});

I believe it will work..

another method is:

function apenas_string(event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode >= 48 && keyCode <= 57 || keyCode == 8 || keyCode == 46 || keyCode == 37 || keyCode == 39) return true;
return false;
}

NOTE: in the keycode above are just numbers, you need to find the letters, but I do not know if employee in Firefox...I know that the way to capture keycode in firefox is different.. so I put var keycode = several methods...

<input type="text" id="xyz" onKeyPress="return apenas_string(event)" >

1

As you quote in the question:

  • I can’t allow numbers to enter

This function will not allow the entry of invalid characters (numeric in your case), can be used together with a final validation, as demonstrated by colleagues.

$(document).ready(function() {
  $("#edt_text").keydown(function (e) {        
    // Ensure that it is a number and stop the keypress
    if ((((e.keyCode < 48 || e.keyCode > 105)) || !(e.keyCode > 57 && e.keyCode < 96))) {
        if(e.shiftKey) return;
        e.preventDefault();
    }
  });
});

Here’s a example working.

1

I think the best solution is to check if the key being pressed corresponds to a number. Something like this should solve the problem:

$('input').on('keypress', function(event) {

    if(/\d/.test(String.fromCharCode(event.keyCode))) event.preventDefault();

});

Browser other questions tagged

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