Click here to Skip to main content
Click here to Skip to main content

Input Masking in MVC 4 using Data Annotation

, 24 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Input masking in model using data annotation


If we want to present dates, phone numbers, etc., you would like them to enter the data in a certain format. You can use easily jquery to mask the input, but the only drawback to this approach is that we need to add those functions for each input to be masked.

In MVC 3/ MVC 4, we can easily achieve this by creating custom data annotation and use it on model.


When I am searching on the Internet, I found nothing which provided Input Masking using data annotation. Only this post provided me with some idea. So, I am working on this and solved the problem.

I am using Masked Input Plugin to mask my input.

Using the Code

First of all, we need to create our own Custom Attribute class.

  public class InputMaskAttribute : Attribute, IMetadataAware
     private string _mask = string.Empty;

    public InputMaskAttribute(string mask)
            _mask = mask;

        public string Mask
            get { return _mask; }

        private const string ScriptText = "<script type='text/javascript'>" +
                                          "$(document).ready(function () {{" +

        public const string templateHint = "_mask";

        private int _count;

        public string Id
            get { return "maskedInput_" + _count; }

        internal HttpContextBase Context
            get { return new HttpContextWrapper(HttpContext.Current); }

        public void OnMetadataCreated(ModelMetadata metadata)
            var list = Context.Items["Scripts"] 
            as IList<string> ?? new List<string>();
            _count = list.Count;
            metadata.TemplateHint = templateHint;
            metadata.AdditionalValues[templateHint] = Id;
            list.Add(string.Format(ScriptText, Id, Mask));
            Context.Items["Scripts"] = list;

Here is the screenshot:

Now, we have to create an extension of View Data.

  public static TAttribute GetModelAttribute<TAttribute>
(this ViewDataDictionary viewData, bool inherit = false) where TAttribute : Attribute
            if (viewData == null) throw new ArgumentException("ViewData");
            var containerType = viewData.ModelMetadata.ContainerType;


and to call the JavaScript, we will implement a method extension called RenderScripts.

 public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
            var scripts = htmlHelper.ViewContext.HttpContext.Items["Scripts"] as IList<string>;
            if (scripts != null)
                var builder = new StringBuilder();
                foreach (var script in scripts)
                return new MvcHtmlString(builder.ToString());
            return null;

Now, we have successfully created a custom attribute. Now, create a Model/ViewModel class and use the newly created attribute.

     public class TestModel
        [Display(Name = "Date")]
        public DateTime Date { get; set; }

        [Display(Name = "Phone")]
        [InputMask("(999) 999-9999")]
        public string Phone { get; set; }

        [Display(Name = "Phone + Ext")]
        [InputMask("(999) 999-9999? x99999")]
        public string Phone_Ext { get; set; }

        [Display(Name = "TaxID")]
        public string TaxID { get; set; }

        [Display(Name = "SSN")]
        public string SSN { get; set; }

        [Display(Name = "ProductKey")]
        public string ProductKey { get; set; }

        [Display(Name = "IP")]
        public string IP { get; set; }

Create a strongly typed view:

 <legend>Input Masking</legend>
        <li>@Html.EditorFor(m=> m.Date)
           <li>@Html.EditorFor(m=> m.Phone)
        <li>@Html.EditorFor(m=> m.Phone_Ext)
        <li>@Html.EditorFor(m=> m.TaxID)
        <li>@Html.EditorFor(m=> m.SSN)
        <li>@Html.EditorFor(m=> m.ProductKey)
        <li>@Html.EditorFor(m=> m.IP)

In ~/Views/Shared/EditorTemplates, add this:

 @model String

@{ var maskedInput = ViewData.GetModelAttribute<InputMaskAttribute>();
   if (maskedInput != null)
        <div class="editor-label">
        <div class="editor-field">
            @Html.TextBoxFor(m => m, new 
            { id = ViewData.ModelMetadata.AdditionalValues[InputMaskAttribute.templateHint] })

You are almost done. Just do one thing, add reference of Masked Input Plugin.

 @section Scripts
        <script src="~/Scripts/InputMask.js"></script>


Here is the output:


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ankit Sarkar
Software Developer Maxmobility Pvt. Ltd.
India India
No Biography provided

Comments and Discussions

QuestionCan't make this work (MVC 3) PinmemberMember 844665017-Jun-14 23:50 
AnswerRe: Can't make this work (MVC 3) PinmemberAnkit Sarkar25-Jul-14 21:35 
Questiongood PinmemberMember 105104506-Mar-14 19:47 
QuestionMade a change to use MVC5 and not using the mask Pinmemberg.david.carter25-Feb-14 11:06 
AnswerRe: Made a change to use MVC5 and not using the mask Pinmemberdjarvis817-Sep-14 11:10 
QuestionPublish on Internet Domain PinmemberMember 1040022514-Nov-13 7:26 
QuestionQuestion PinmemberMember 1040022513-Nov-13 15:22 
AnswerRe: Question PinmemberAnkit Sarkar13-Nov-13 16:18 
AnswerRe: Question PinmemberMember 1040022515-Nov-13 9:18 
QuestionWhere can I download . PinmemberMember 39187109-Oct-13 3:55 
AnswerRe: Where can I download . PinmemberAnkit Sarkar9-Oct-13 17:12 
GeneralMy vote of 5 PinmemberdgDavidGreene26-Aug-13 12:42 
GeneralMy vote of 5 PinmemberAnurag Gandhi25-Aug-13 4:18 
GeneralMy vote of 5 PinprofessionalHasibul Haque24-Aug-13 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 24 Aug 2013
Article Copyright 2013 by Ankit Sarkar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid