Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
mark vanzuela Avatar asked Nov 09 '09 05:11

mark vanzuela


People also ask

How check textbox value is numeric or not in jQuery?

jQuery isNumeric() method The isNumeric() method in jQuery is used to determine whether the passed argument is a numeric value or not. The isNumeric() method returns a Boolean value. If the given argument is a numeric value, the method returns true; otherwise, it returns false.

How do I allow only numbers in a text box?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number.

Which of the function is used to check textbox only contain numbers?

You can check if the user has entered only numbers using change event on input and regex. $(document). ready(function() { $('#myText').


1 Answers

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);
});
like image 159
TheVillageIdiot Avatar answered Oct 02 '22 12:10

TheVillageIdiot