Monday, 24 February 2014

Restrict html tags in textbox

At times you might encounter situations where the customer wants to restrict certain characters from being entered into a textbox. A common scenario is to restrict users from entering the html tags like < and > symbol from being entered into the textbox.
Using javascript you can achieve this very easily. What you need to understand here are the different events that gets fired when we press any key on the keyboard.
  1. KeyDown - A key is pressed down.
  2. KeyPress - A character key is pressed
  3. KeyUp - A key is released.
Now although KeyDown and KeyPress may seem to be the same but they are not. Keydown is triggered on any key press. KeyPress triggers after KeyDown event but it is only guaranteed for character keys.

So, after having this basic understanding, we can move ahead with the requirement and that is to restrict users from entering the "<" and ">" characters.

function RestrictTags(sender, event) {
        var key = event.which ? event.which : event.keyCode;
        var shiftKey = event.shiftKey;
        if ((shiftKey == true) && ((key == 188) || (key == 190))) {
            return false;
        return true;
The above code snippet shows how you can restrict "<" and ">" tags from being entered. Let me briefly explain you what the above piece of code does.

event.which - It returns the numeric keyCode of the key pressed or the character code (charCode) of the alphanumeric key pressed.
event.shiftKey - It is a boolean attribute that helps in identifying if a shift key is pressed or not.

So, if you look at the keyboard, in order to press the "<" or ">" key, you need to press the Shift key and then the "<" and ">" key.

188 is the keyCode for both , and <
190 is the keyCode for both . and >

So, in order to differentiate whether 188 is coming because of comma or less than symbol key press and 190 is coming because of period key or greater than key pressed, you make use of event.shiftKey.
So if you have the event.shiftKey attribute set to true and the keyCode is 188 that means you have pressed > . Similarly if you have event.shiftKey to true and the keyCode is 190 that means you have pressed <.

So that explains the if condition above. Rest is self explanatory. Calling the above method on the keydown event, you can restrict the user from entering the > and < characters.

You can call the event like below

<input id="txtName" type="text" onkeydown="return RestrictTags(this,event);"/>

Hope that helps !!!

No comments:

Post a Comment