mcxiand mcxiand - 6 months ago 7
jQuery Question

Validate numeric text field in jquery

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?

Answer

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);
});