Wednesday, April 24, 2013

How To- Validate Numeric Values only in TextBox using Java Script/jQuery

In this post, I will explain how to validate user to enter only numeric values in TextBox using jQueryJava Script.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to jQuery, Java Script etc.

To validate numeric values in TextBox, we need to write the following jQuery or Java Script function.

Using Java Script

Create the following function for validate numeric values in TextBox
function isDigit(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (((charCode == 8) || (charCode == 46) || (charCode >= 35 && charCode <= 40) || (charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)))
    { 
      return true;
    }
    else
    { 
  return false;
    }      
}
Now call the isDigit function as shown below-

<asp:TextBox id="txtNumeric" onkeydown="return isDigit(event)" runat="server"></asp:TextBox>

 

Using jQuery

Write the following code for validate numeric values in TextBox
$(function () {
$('#TextboxId').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;   
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
});

Live Demo


I hope this article will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo