paul
paul

Reputation: 1124

validating numeric values in text box

I have to allow user to allow only numeric values in the text box . It should remove any non numeric method. No matter how they are supplying the input ...either typing or copy+paste.

My code

var nCheck  = function (field) {
var re = /^[0-9]*$/;
               if (!re.test(field.value)) {

                       field.value = field.value.replace(/[^0-9]*$/g,"");
               }
 };

This works except when you copy paste something like aaa2 . Whereas aaaa or aa work. Problem is when last place contains number it fails .

Thanks for any help.

Upvotes: 0

Views: 3407

Answers (4)

iambriansreed
iambriansreed

Reputation: 22241

No regex:

field.value = isNaN(field.value) ? '' : field.value;

Upvotes: 0

SJuan76
SJuan76

Reputation: 24780

The $ means "end of string". Remove it and it should work.

Other tips:

Replace * by +; * includes the empty string

Maybe it should better to warn the user, just in case the numeric character is a typo (like pressing Q instead of 1)

Upvotes: 2

cambraca
cambraca

Reputation: 27839

Just do

field.value = field.value.replace(/[^0-9]/g,"");

This will replace everything that's not a number for nothing, and you don't even have to run the test function.

Upvotes: 4

Josh Mein
Josh Mein

Reputation: 28625

If you use jQuery, check out textola a jquery numeric plugin.

Upvotes: 0

Related Questions