Let us first prepare a user friendly warning image that says message to enter numeric characters. |
In key press event of the text box we call a java script function.
function ChkNumericCharacters(tid,imgPth,x,y)
{
if(!isNumericChar(event.keyCode)) //Checking whether user typed in character is numeric
{
//If not numeric, then displaying the above created image in a label inner HTML.
// Also return false, helps to not get the types character into text box.
showToolTip(tid,imgPth,x,y);
return false;
}
else
{
//IF typed in character is numeric, then hiding the image if visible.
HideToolTip();
return true;
}
}
function isNumericChar(val)
{
//function to find whether typed in charater is available in the considered numeric characters.
var strval=String.fromCharCode(val);
var str='1234567890';
if(str.toUpperCase().indexOf(strval.toUpperCase())==-1)
{
return false;
}
else
{
return true;
}
}
function showToolTip(tid,txt,xsh,ysh)
{
//function to display user friendly image at the location near to the text box.
var theTip = document.getElementById("spnTip");
var crd=findPosition(document.getElementById(tid));
theTip.style.top=crd[1]+ysh;
theTip.style.left=crd[0]+xsh;
//assiging the image as inner html to the label.
theTip.innerHTML ="<img src='"+txt+"' />";
theTip.style.visibility = "visible";
}
function HideToolTip()
{
//To set the visibility hidden for the image
var theTip = document.getElementById("spnTip");
theTip.innerText = '';
theTip.style.visibility = "hidden";
}
//Html label whose position is absolute, such that its position can be changed dynamically.
<label id="spnTip" style="position:absolute; width:100px;visibility:hidden;background:lightyellow;
border:1px solid gray;padding:2px;font-size:8pt;font-family:Verdana;" onmouseout="hideTip()"></label>
<asp:Label ID="lblMessage" runat="server" Font-Bold="True" Font-Size="XX-Small" ForeColor="#C00000"></asp:Label>
In code behind page I say,
txtBox.Attributes.Add("onkeypress", "return ChkNumericCharacters('" + txtBox.ClientID + "','../Images/NumericChrcter.bmp',20,30);"); in page load event of the page, for text box to which we are willing to handle numeric characters valiadtion
I can either call this function in aspx.cs or from aspx page.
Output when user enters non numeric character :
No comments:
Post a Comment