views:

1452

answers:

3

I have this code in jquery to prevent non-numeric characters being inputted to the text field

$("#NumericField").numeric();

Now, on the text field i cant input non-numeric characters. That is OK. The problem here is if the user will paste on the text field with non numeric characters.

Is there a way/method to disable pasting if the value is non-numeric? Or is there any other approach to handle this situation that you can share?

+4  A: 

you can use callback which checks on leaving field if value is valid if value is not valid then clear it and show error message:

var decimal_char = ',';
function isvalidnumber(){
    var val=$(this).val();
    //This regex is from the jquery.numeric plugin itself
    var re=new RegExp("^\\d+$|\\d*" + decimal_char + "\\d+");
    if(!re.exec(val)){
     alert("Invalid number");
     $(this).val("");
    }  
}
$(document).ready(function(){
    $("#txtN").numeric(decimal_char,isvalidnumber);
});
TheVillageIdiot
Maybe instead of an error message the input could just be filtered to remove the illegal characters? It could be nicer for the user if he/she pastes a number that has a space in the end, for example.
Kaivosukeltaja
I've modified it. first one was not working and not taking into account decimal char
TheVillageIdiot
I will try this one...
mcxiand
Alert? are you kdding me :)
bortao
@borato this was just to illustrate.
TheVillageIdiot
+1  A: 

I found this script on http://www.kunalbabre.com/jQueryLibrary/index.php:

$('input[numeric]').keyup(function() {

        var d = $(this).attr('numeric');

        var value = $(this).val();
        var orignalValue = value;
        value = value.replace(/[0-9]*/g, "");

        var msg = "Only Integer Values allowed.";

        if (d == 'decimal') {
            value = value.replace(/\./, "");
            msg = "Only Numeric Values allowed.";
        }
        if (value != '') {
            orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
            $(this).val(orignalValue);
            //alert(msg);
            $(this).after('<span style="margin-left:5px;color:red;position:absolute;">' + msg + '</span>');
        }
        else {
            $(this).next('span').remove();
        }

    });

It works fine except if the number has ',' on it like '100,000.00'. It will render just '100'. The ',' and the rest are gone.

Edit: I think this is on the reg ex but im clueless about it. :(

Any Idea? Help?

mcxiand
+1  A: 

Where it says:

value = value.replace(/\./, "");

You should put:

value = value.replace(/\.\,/, "");

I guess ;-)

I really ended up doing this:

$(‘.InputClass’).keyup(function(){
  if ($(this).val() != "")
     $(this).val( $(this).val().replace(/[^0-9\.]/g, "") );
});

So, no anoying alerts nor anything; just if you type anything else than a number or a dot after a number, is wipped out. Simple but efective.

Cheers. Hope helps someone.

1ukaz