Ethan
Ethan

Reputation: 60089

How can I prevent entry of non-numerals a text field?

I found this question. However, most of the answers intercept the key press, check the key code, and stop the event if it isn't an acceptable key code.

There are a some problems with that.

I would like a solution that allows the keypress, then checks the entered value against a regex and removes unwanted characters.

I'm looking for a solution along these lines:

I tried this function:

  $('input.numerals_only').keypress(function() {
    var v = $(this).val();
    var no_nonnumerals = v.replace( /[^0-9]/, '' );
    $(this).val(no_nonnumerals);
  });

But that doesn't work. I'm still able to type in letters.

Any info on why it doesn't work? How could I modify it so it works? Other suggestions?

Upvotes: 2

Views: 2121

Answers (5)

Brian
Brian

Reputation: 1

I wrote a jQuery plugin to do this. Demo and code here http://brianjaeger.com/process.php

It uses a regular expression to validate whatever you want.

There are a few issues:

  • it's a plugin (however, you could suck out the code and plunk it into your other JavaScript if you want. -its easier just to use as plugin)
  • Unfortunately there is no way to limit pasted information directly (across all browsers) - My solution to this was to add validation on focus change as well as keypress.

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

If you use keyup and also blur you should handle most cases. Someone keys in text and also if they paste in a value into the text box. As the blur function will remove the bad values as well.

$('input.numerals_only').keyup(AllowOnlyNumber).blur(AllowOnlyNumber);

function AllowOnlyNumber()
{
    var v = $(this).val();
    var no_nonnumerals = v.replace(/[^0-9]/g, '');
    $(this).val(no_nonnumerals); 
}

Of course if html5 is an option you could always do:

<input type="number"/>

jsfiddle example.

Upvotes: 2

Kissaki
Kissaki

Reputation: 9217

The thing your regexp is missing, which is why it didn’t work for keypresses neither, is the g flag for a global regexp check.

Use var no_nonnumerals = v.replace( /[^0-9]/g, '' );

Upvotes: 2

Annabelle
Annabelle

Reputation: 10716

Use the keyup event. It is triggered after the key is processed by the browser:

$('#txtInput')
    .keyup(function(ev) {
        var newValue = this.value.replace(/[^0-9]/, '');
        $(this).val(newValue);
    });

Upvotes: 0

Wolph
Wolph

Reputation: 80031

If you use keyup instead of keypress it will always remove the incorrect characters.

You can also use this to actually block the events:

$('input.numerals_only').keypress(function(event) {
    if(event.keyCode < 48 || event.keyCode > 57){
        return false;
    }
});

Upvotes: 1

Related Questions