How to create a masked textbox using JavaScript
July 8, 2009 – 12:19 amThis article demonstrates how to implement a masked input box or masked textbox using JavaScript. For example, let’s imagine you have a simple HTML form and want to restrict the user to enter on numbers in a Telephone number field. The following code will demonstrate how to to capture the keypress events of a form element (eg. your Telephone input textbox) and to restrict which keys can be pressed.
<script>
function maskedTextbox(evt) {
var e = evt || window.event;
var pK = evt.which || e.keyCode;
var keyPressed = String.fromCharCode(pK);
var reDigit = /^\d$/;
var reCTRLChars = /[\x63\x78\x76\x7A]/; // Non-IE: cut, paste, etc. IE lets CTRL operations through.
var reAllowedCodes = /[\x00\x08\x23\x24\x25\x26\x27\x28\x2D\x2E]/; // arrow keys, ins, del, hom, end, bspace
if (reCTRLChars.test(keyPressed) || reAllowedCodes.test(keyPressed) || reDigit.test(keyPressed)) {
return true;
}
return false;
}
</script>
<-- Normal HTML example -->
<input type="text" onkeypress="return maskedTextbox(event);" />
<-- ASP.NET C# example -->
<asp:TextBox ID="txtEmail" onkeypress="return maskedTextbox(event);" runat="server" />
The example demonstrates restricting input to an HTML form element by capturing the onkeypress event. The javascript function will check which key was pressed and return true or false based on whether the keypress is allowed or not. The particular example restricts input to only numbers (ie. 0 to 9). However, there are some other characters we must allow through - INSERT, HOME, DELETE, END, BACKSPACE, and the ARROW keys.