Search All Articles Submit your Website or Blog to A New Internet Library
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)"
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.


4 comments:
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.
Hi Brandon,
Can you please explain your suggestion in detail.
This was exactly what I needed. Thank you.
Tommy Newcomb
www.verifyhistory.com
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.