Search All Articles Submit your Website or Blog to A New Internet Library
Friday, January 2, 2009
How to disallow user to enter special charaters in HTML input type text.
Say we have HTML input control with type text for accepting Name from the user.
Here we should not allow special characters to be entered except few characters like (',-).
for doing this in HTML we will create Javascript function which does this and call this function on "onkeypress" event.
function ValidateName(name,e)
{
// To handle copy paste scenarios
// replace unmaching characters in textbox value with empty
var nameRegex = /^[A-Za-z',.-]{0,50}$/;
while (!name.value.match(nameRegex)) {
name.value = name.value.replace(/[^a-zA-Z,'.-]+/, "");
}
//FF and IE
e = e || window.event;
var allow = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,'-";
var keycode = e.which || e.keyCode; //For both FF and IE
if (allow.indexOf(String.fromCharCode(keycode)) < 0 && keycode != 13 && keycode != 0)
{
return false;
}
return true;
}
Form allow character string as "abc...zAB..Z,'.-" then checking the typed key (by user), then return false if it not matches with any of the allowed characters.
To handle copy paste scenarios. Write regular expression to allow requered charaters(in my case A-Za-z',.-), then replace unmaching characters in textbox value with empty. Use while loop to remove all umatching group of characters.
calling this function as
<input type="text" name="txtName" id="txtName" onkeypress="return ValidateName(this,event);" onchange="return ValidateName(this,event);" />
Hey one more important thing if user uses mouse to copy and paste name and then clicks on submit button by mouse then onkeypress will not work so better if we also use "onchange" or "onblur" event too, to call the same function.
Subscribe to:
Post Comments (Atom)
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.


1 comment:
the ValidateName is not the opmtimal solution, as it stops you from using the the direction and backspace in any field you apply it on
Post a Comment
Post your comments/questions/feedback for this Article.