Hi guys, In this post i m going to explain how to perform numeric value validation in a TextBox in ASP.NET. Here i will post two diff. mechanism by using Java Script and JQuery. 1. Using Java ScriptIn the heading part. write down following lines of code..
//Java Script function to check the nemeric values in a text box only
function checkIt(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false
}
return true
}
In the body .."In text Box"
onkeypress="return checkIt(evt)"
2. Using JQuery
//JQuery function to check the nemeric values in a text box only
function TestNumber() {
var keyPressed;
if (!e) var e = window.event;
if (e.keyCode) keyPressed = e.keyCode;
else if (e.which) keyPressed = e.which;
var hasDecimalPoint = (($(this).val().split('.').length - 1) > 0);
if (keyPressed == 8 || ((keyPressed == 190 || keyPressed == 110) && (!hasDecimalPoint)) || keyPressed == 9 || keyPressed == 27 || keyPressed == 13 ||
// Allow: Ctrl+A
(keyPressed == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(keyPressed >= 35 && keyPressed <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (keyPressed < 48 || keyPressed > 57) && (keyPressed < 96 || keyPressed > 105)) {
e.preventDefault();
}
}
}
// Invoke TestNumber() using Jquery
$(document).ready(function () { $("#t1").keydown(function (e) { TestNumber() }); });
$(document).ready(function () { $("#t2").keydown(function (e) { TestNumber() }); });