Introduction
I was looking for a simple way to apply input masks for phone number fields and it seems like there's no built-in way to do this in ASP.NET MVC. I found this CodeProject article to be quite helpful -> http://www.codeproject.com/Tips/642477/Input-Masking-in-MVC-using-Data-Annotation. I learned quite a bit from this and it led me to a jquery plugin called jquery.maskedinput. Thanks to the author, Ankit Sarkar! While this approach might be good, I found it to be a bit complex. The idea of having a property attribute that we can just decorate on properties where we want input masking to be applied is actually great, but I wish this was built-into ASP.NET as I really don't want to maintain the code and templates to support this custom attribute.
Using jquery.maskedinput
and Html.TextBoxFor
, we can create input masks on textbox
fields without the need for custom attributes and custom editor templates.
Steps
1. Add jquery.maskedinput Plugin to your Solution
Download jquery.maskedinput and add this to your BundleConfig.cs.
bundles.Add(new ScriptBundle("~/bundles/jquerymask").Include(
"~/Scripts/jquery.maskedinput*"));
2. Create the Input Mask Binder Script
Create a new script, save it as maskedinput-binder.js and write the following code in the script:
$(function () {
$('[mask]').each(function (e) {
$(this).mask($(this).attr('mask'));
});
});
3. Add the maskedinput-binder.js Script to your jquerymask Bundle
bundles.Add(new ScriptBundle("~/bundles/jquerymask").Include(
"~/Scripts/jquery.maskedinput*",
"~/Scripts/maskedinput-binder.js"));
4. Add the Mask Attribute on Your textboxes
@Html.TextBoxFor(model => model.PhoneNumber, new {mask = "(999) 999-9999" })
5. Add the Script Bundle in your Scripts Section on the View
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jquerymask")
}
That's it! Your input fields are now masked.
Points of Interest
One thing to keep in mind here is that the input mask is all on the client side, so you might want to add regex validation on your model fields.
I tested the input mask on a mobile device, Samsung Galaxy 4 with Chrome, and discovered the masking is unwieldy. The cursor has to be set at the far right end of the input box in order for your input to output in the correct order. If the cursor is anywhere else, the output of your text entry is not in the correct order.
In my opinion, I think this is a very generic approach that can be applied to a lot of other client side plugins you want to work with. The basic idea is we just output attributes on controls and we let the client side plugin/jquery do all the work.
History
- 26th November, 2014 - Submitted