HowTo: use jQuery input mask plugin in ASP.NET

Today I’ve got a requirement to force the user input to follow this international phone number format “(country-code) 1234-568” & because I love jQuery I started to look for an input mask plugin, I found this one.

So I built simple ASP.NET Web Application to start playing with it. It’s contains 3 TextBoxes/Input fields, first one for the landline phone number, second one for mobile phone number, & the third and last one for the date of birth.

Here’s the aspx code snippet:

maskedinput

As you can see I’m using the new ASP.NET 4 feature ClientIDMode so I can select the 3 textboxes by their #IDs not by CSS .classes, why ID not Class? because of performance check this article point no 4.

The solution file:

  • Hoodwink

    Thanks!!

  • sampath

    Good one.Keep it up.

    • EmadMokhtar

      Thanks and I’;m glad you like it

  • pooja dhingra

    Hi,

    I am using the same code but i am not getting this functionality, But if i use this code in a simple html page, then it works but i need it on a web form. can any1 tell me what i am missing here???

    Thanks in advance,

  • mostafa

    if this code not work in asp page cheek this parameter ( ClientIDMode=”Static”)

    • EmadMokhtar

      Mostafa,

      It’s working with me and I attached a screenshot of running ASP.NET application, and ClientIDMode=”Static” to tell ASP.NET to render the ID of control as the ID you defined in code, that make this selecting $(“#txtPhoneNumber”) works

  • Alex

    Hi, how about country codes? The value inside (…) is not the one, it’s a regional/mobile operator code. Country code should look like this /^+[1-9]{1}[0-9]{1,3}/ (or something like that) at the beginning of the .mask(“(999) 9999-9999”). Is it possible to allow different masks for the same field depending of the country code? Or at least make the number length flexible?

    Thanks,
    Alex

    • EmadMokhtar

      You can implement this in JavaScript for example:

      if(countryCode == ‘EG’){
      $(“#txtPhoneNumber”).mask(“(999) 9999-9999”);
      }
      else{
      $(“#txtPhoneNumber”).mask(“(9999) 9999-9999”);
      }

  • Arnab patra

    hi how about the money?and what should i do if the field is mandatory? will it also validtae mandatory/non empty fields?

  • Shanaya Singh

    its nice but i have found another example to implement masking/unmasking in asp.net refer to http://www.etechpulse.com/2016/01/jquery-mask-unmask-example.html

    • http://www.emadmokhtar.com Emad Mokhtar

      The code is switching the property of the input tag between password and text based on the status of the checkbox, it’s jQuery code, but what i wrote about is jQuery lug-in.
      If this solution satisfy your needs then use it because it’ll remove the plug-in code from the application and just using jQuery.