Tuesday, December 2, 2008

How to handle special characters using java script

Don’t allow special characters using java script.

We use input type=’text’ as html content in web applications to display a text box component. We can restrict user from entering special characters in a text box by handling key press event of the text box.




Let us first prepare a user friendly warning image that says message to not enter special characters.







In key press event of the text box we call a java script function.


function ChkSpecialCharacters(tid,imgPth,x,y)
{

if(isSpecialChar(event.keyCode))
{
showToolTip(tid,imgPth,x,y);
return false;
}

else
{
HideToolTip();
return true;
}

}

function isSpecialChar(val)
{
var strval=String.fromCharCode(val);
var str='abcdefghijklmnopqrstuvwxyz1234567890';
if(str.toUpperCase().indexOf(strval.toUpperCase())==-1)
{
return true;
}
else
{

return false;
}
}

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>


In code behind page I say,

txtBox.Attributes.Add("onkeypress", "return ChkSpecialCharacters ('" + txtBox.ClientID + "','../Images/SpclChrcter.bmp.bmp',20,30);"); in page load event of the page.

I can either call this function in aspx.cs or from aspx page.


Output when user enters special character :





No comments: