Saturday, October 25, 2008

Numeric Validation Using JavaScript

<asp:textbox id="TextBox1" runat="server"
onkeypress="return detectEvent(event);"
onkeydown="return detectEvent(event);"></asp:textbox>


onkeydown
onkeypress


we are using both the event since some
browsers don't have one of the event.


To accept only numbers both from NUMPAD and
from KeyBoard we use this method.

function detectEvent(e) {
var evt = e || window.event;
// Firefox
if(evt.type == 'keydown') {
if ( (evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96
&& evt.keyCode <= 105) ) return true;
return false;
}
else if(evt.type == 'keypress') {
if (evt.charCode >= 48 && evt.charCode <= 57) return true;
return false;
}
}

This one for IE since IE don't have charCode

function detectEvent(e) {
var evt = e || window.event;
// IE
if(evt.type == 'keydown') {
if ( (evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96
&& evt.keyCode <= 105) ) return true;
return false;
}
else if(evt.type == 'keypress') {
if (evt.keyCode >= 48 && evt.keyCode <= 57) return true;
return false;
}
}


Now a common method for both the things(it works both in IE and FireFox
for both NUMPAD and for KeyBoard)

function validKey(e) {
var KeyID = window.event ? event.keyCode : e.which;
var evt = e || window.event;
if(evt.type == 'keydown') {
if ( (KeyID >= 48 && KeyID <= 57) || (KeyID >= 96 && KeyID <= 105) ) return true;
return false;
}
else if(evt.type == 'keypress') {
if(KeyID >= 48 && KeyID <= 57) return true;
return false;
}
}

No comments: