Thursday, May 29, 2014

How to create MaskedTextBox custom control in Asp.net?

A Masked Textbox is very handy when you want to put a mask for "Phone, SSN or Date" Fields throughout the project. Especially, when you have many places in your project where you have to do masking on textboxes. Masking is useful because it prevents a user from entering wrong inputs. If we create custom control for Masking, it will be easier for us to just drag and drop control and apply masking format like
for U.S. Phone-> (999) 999-9999 where 9 represents digit only. So the question is how to create a custom control... and here it is:

You can do this by JQuery and VB/C# class. You need two files of JQuery:
1. jquery-1.9.1.min.js
2. jquery.maskedinput.min.js
You can download these two files from :
http://jquery.com/
http://digitalbush.com/projects/masked-input-plugin/

And one VB/C# Class file. Following is the VB.net code:

Public Class MaskedTextBox
    Inherits TextBox


    Private _cMast As String
    Public Property cMask() As String
        Get
            Return _cMast
        End Get
        Set(ByVal value As String)
            _cMast = value
        End Set
    End Property


    Private Sub MaskedTextBox_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim scriptText As String



        scriptText = "<script src="jquery-1.9.1.min.js"></script>" _
            + "<script src="jquery.maskedinput.min.js"></script>" _
            + "<script>$(document).ready(function() {" _
            + "$('#" + Me.ID + "').mask('" + cMask + "');" _
            + "$('#" + Me.ID + "').click(function () { " _
            + "if (document.getElementById('" + Me.ID + "').value == '" + cMask.Replace("9", "_") + "') {" _
            + "setCaretPosition('" + Me.ID + "', 0) }" _
            + "});" _
            + "});</script>"



        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            Me.ID + "t", scriptText)

        scriptText = "<script>function setCaretPosition(elemId, caretPos) { " _
            + "var el = document.getElementById(elemId);" _
            + "el.value = el.value;" _
            + "if (el !== null) {" _
            + "if (el.createTextRange) {" _
            + "var range = el.createTextRange();" _
            + "range.move('character', caretPos);" _
            + "range.select();" _
            + "return true;}" _
            + "else {" _
            + "if (el.selectionStart || el.selectionStart === 0) {" _
            + "el.focus();" _
            + "el.setSelectionRange(caretPos, caretPos);" _
            + "return true;}" _
            + "else {" _
            + "el.focus();" _
            + "return false;}}}}</script>"


        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            "setCursor", scriptText)


    End Sub
End Class

Once you create this class file in your project. you have to register this control wherever you want to use. you can register it either on the page or in web.config if you want to use throughout the project.

For web.config:
<configuration>

  <system.web>
    
    <pages>
      <controls>
         <add assembly="CustomControls" namespace="CustomControls" tagprefix="cc">
      </add>
    </controls>
    </pages>

  </system.web>
</configuration> 


For .aspx page:
<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>

Complete .aspx page code:
<%@ Page Language="vb" AutoEventWireup="false" 
    CodeBehind="Default.aspx.vb" Inherits="CustomControls.WebForm1" %>

<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>
   
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MaskedTextBox<title/>
</head> 
<body> 
<form id="form1" runat="server"> 

U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone" runat="server" 
 cMask="(999) 999-9999" /> 
U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone1" runat="server"
 cMask="(999) 999-9999" />  
SSN 1: 
<cc:MaskedTextBox ID="mtxtSSN" runat="server"
 cMask="999-99-9999" /> 
SSN 2: 
<cc:MaskedTextBox ID="mtxtSSN1" runat="server"
 cMask="999-99-9999" /> 

</form> 
</body> 
</html> 


Final Result and sample project structure will look like this:

3 comments:

  1. Magnificent beat ! I would like to apprentice while you amend
    your website, how can i subscribe for a blog
    site? The account aided me a acceptable deal.

    I had been a little bit acquainted of this your broadcast provided bright clear idea

    ReplyDelete
  2. I do not even know how I ended up here, but I thought this post was good.
    I don't know who you are but definitely you're
    going to a famous blogger if you aren't already ;) Cheers!

    ReplyDelete
  3. Hi, just wanted to mention, I loved this post. It was inspiring.

    Keep on posting!

    ReplyDelete

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...