↑ Grab this Headline Animator

Friday, September 18, 2009

Validating textbox to not allow invalid characters in all cases.

In order to allow user to enter only certain characters in a textbox and also to control the maximum length of multiline textbox use the below function by calling it on onkeypress for a textbox.

And also to handle the cases where the user copy paste the content containing the invalid characters first we will prepare the regular expression to and check for invalid characters and replace with empty (remove invalid characters from pasted content).

Then we will get the pressed key and check the key pressed by user while entering the text into a textbox and check if it is in part of valid character and based on which we will stop user from entering invalid characters.

One important thing here is we need to allow few keys like backspace, Arrow keys, Home, End etc.. for that we will make sure that the key pressed is not in (27, 9, 32, 8, 36, 37, 35, 13, 0).

function ValidateName(name,e)
var nameRegex = /^[A-Za-z',.-]{0,50}$/;
while (!name.value.match(nameRegex))
name.value = name.value.replace(/[^a-zA-Z,'.-]+/, "");
e = e || window.event;
var allow = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,'-";
var allowKeys = new Array(27, 9, 32, 8, 36, 37, 35, 13, 0);
var keycode = e.which || e.keyCode;
if (allow.indexOf(String.fromCharCode(keycode)) < 0)
for (var i = 0; i < allowKeys.length; i++)
if (allowKeys[i] == keycode)
return true;
return false;
return true;

Call this function in onkeypress event as shown below.

Onkeypress = "return ValidateName(this,event)"

Submit this story to DotNetKicks


Brandon Slezak said...

Personally I would rather use .NET code to extract the perfmon value for messages in queue. This is light years faster than enumeration because you can just extract it immediately from perfmon, especially if there are thousands of messages.

Anonymous said...

Hi Brandon,

Can you please explain your suggestion in detail.

Tommy Newcomb said...

This was exactly what I needed. Thank you.

Tommy Newcomb

Anonymous said...

this code doesn't work well in ie8
You can run into situations where it loops and hangs the browser.

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles