Thursday, December 23, 2010

Simple JQuery Plugin to Format Validate a U.S Telephone number

Recently I needed a simple Validation component which would take care of auto formatting the content entered in a text box to a U.S phone number (NPA)-NXX-XXXX. As I was using JQuery, I thought of writing a simple plug-in to do the same. Sharing the code here, just in case this is useful for someone else

The plug-in does the following

       1. Formats the number to (NPA)-NXX-XXXX as it is typed
       2. It will not allow you to enter special characters or non-number in the textbox.
       3. It will validate that you can enter only 10 digits
       4. This plug-in as of now does not support chaining as I did not see a need.
    
    

       The code and the HTML Snippet are shown below. Please do add a comment for any bugs.

      Plug-in code : Save this as whatever JS file you need it to be - I have used jquery.usphone.js in the HTML

      (function( $ )
      {
        // This function formats a text field to a US 
        // phone number as the user types the information.
       
        $.fn.usphone = function() 
        {
          this.keyup(function() 
          {
           var curchrindex = this.value.length;
           var curval = $(this).val();
           var strvalidchars = "0123456789()-";
                
           for (i =0; i < this.value.length; i++)
           {
            var curchar = curval[i];
            if (strvalidchars.indexOf(curchar) == -1) 
            {
             //delete the character typed if this is not a valid character.
             $(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
            }
           }
           
           // Insert formatting at the right places
           if (curchrindex == 3) 
           {
            $(this).val("(" + curval + ")" + "-");
           }
           else if (curchrindex == 9)
           {
            $(this).val(curval + "-");
           }
           
           //Do not allow more than 15 characters including the brackets and the "-"
           if (curchrindex == 15) 
           {
            //delete the last character typed 
               $(this).val(curval.substring(0, this.value.length-1 ));
           }
           
          });
        };
      })( jQuery );
      
      
      
      

      The HTML code to use this plug-in

      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Insert title here</title>
      <script type="text/javascript" src="./scripts/jquery.js"></script>
      <script type="text/javascript" src="./jquery.usphone.js"></script>
      </head>
      
      <body>
          Please Enter a Valid US Phone number : 
          <input type = "text" id = "phonenumber" />
      </body>
      
      <script>
          $('#phonenumber').usphone();
      </script>
      
      </html>
      

      71 comments:

      1. Anonymous4:21 PM

        Cool, this was useful. thanks !

        ReplyDelete
      2. Found Issues : I do not validate if some one types a # and then changes one digit to a letter :-)

        Will need to validate entire string every time!!!

        ReplyDelete
      3. Fixed the above issue, user can always remove the formatting by deleting it, not handling it for now.

        ReplyDelete
      4. Anonymous11:42 PM

        keep posting like this it’s really very good idea, you are awesome!

        paxil

        ReplyDelete
      5. Anonymous7:19 AM

        Really like your web sites particulars! Undoubtedly a wonderful offer of knowledge that is extraordinarily helpful. Keep on to hold publishing and that i’m gonna proceed studying by way of! Cheers.

        ReplyDelete
      6. Anonymous7:32 PM

        cool Post
        Perfect Solution for U.S Telephone format

        ReplyDelete
      7. I found this help full and simpler than others it just needs some tweaks to support more browsers especially iOS, there is also an issue when deleting. special char like delet and backspace and iphone del need special attention this should help you improve this plug in.

        things to note:

        previous code did not support deleting past the "-" or the ")" because the code with simply insert the val() again.

        also you need a way to determine the index without including the special characters "()-" since this causes a problem too.

        good luck and since you know your code better im sure you will improve it good job.

        /*-----------------------*/
        (function( $ )
        {
        // This function formats a text field to a US
        // phone number as the user types the information.

        $.fn.usphone = function()
        {
        this.keyup(function(e)
        {
        //the key bein presses--------
        var k=e.which;

        var curchrindex = this.value.length;
        var curval = $(this).val();
        var strvalidchars = "0123456789()-";

        for (i =0; i < this.value.length; i++)
        {
        var curchar = curval[i];
        if (strvalidchars.indexOf(curchar) == -1)
        {
        //delete the character typed if this is not a valid character.
        $(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
        }
        }

        // Insert formatting at the right places
        if (curchrindex == 3 && determineKey(k) == true)
        {
        $(this).val("(" + curval + ")" + "-");
        }
        else if (curchrindex == 9 && determineKey(k) == true)
        {
        $(this).val(curval + "-");
        }

        //Do not allow more than 15 characters including the brackets and the "-"
        if (curchrindex == 15)
        {
        //delete the last character typed
        $(this).val(curval.substring(0, this.value.length-1 ));
        }

        });

        //function to determine if user is using these keys witch need special treatment
        function determineKey(e) {
        var k=e;
        //define iPhone
        var iPhone = (window.orientation != undefined);

        //backspace, delete, and escape get special treatment
        if(k == 8 || k == 46 || (iPhone && k == 127)){
        return false;
        } else if (k == 27) {//escape
        return false;
        } else {
        return true;
        }
        };

        };
        })( jQuery );

        ReplyDelete
      8. It does not work in IE 8. In fact using IE 8, it just does not allow you to type in the phone number

        ReplyDelete
      9. Your pluggin does not work if the use just keeps the key pressed in.

        Also does not work in IE 8

        Morever it allows the user to type in any number of digits in the textbox.

        Here is my code with all the fixes

        $.fn.usphone = function () {
        this.keyup(function () {

        $(this).keypress(function () {
        var curchr = this.value.length;
        var curval = $(this).val();
        if (curchr == 3) {
        $(this).val("(" + curval + ")" + "-");
        } else if (curchr == 9) {
        $(this).val(curval + "-")
        }
        else if (curchr = 14) {
        $(this).val(curval.substring(0, curchr - 1));
        }
        });

        });
        };

        ReplyDelete
      10. Mohamed Azath1:06 AM

        Thanks for your help

        ReplyDelete
      11. Anonymous1:26 AM

        I'm impressed, I must say. Seldom do I come across a blog that's equally educative and entertaining, and let
        me tell you, you have hit the nail on the head. The
        problem is something that too few men and women are speaking intelligently about.

        I am very happy I came across this in my search for something concerning this.
        Feel free to visit my web page ... free teen porn

        ReplyDelete
      12. Anonymous5:58 AM

        I pay a quick visit daily some blogs and websites to read articles, however this webpage gives feature based content.
        Also visit my site electronic delivery

        ReplyDelete
      13. Anonymous7:49 AM

        Hi would you mind sharing which blog platform you're using? I'm going to start my own blog soon but I'm having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something unique.

        P.S My apologies for being off-topic but I had to ask!
        my webpage :: android tablet pc

        ReplyDelete
      14. Anonymous1:14 AM

        In fact no matter if someone doesn't understand then its up to other users that they will assist, so here it occurs.
        Here is my web page : High Desert

        ReplyDelete
      15. Anonymous7:26 AM


        Nice post. I learn something totally new and challenging on sites I stumbleupon every day. It will always be helpful to read through articles from other authors and practice something from other web sites.

        ReplyDelete
      16. Anonymous11:36 PM

        Hey there, You've done a great job. I'll certainly digg it and personally suggest to my
        friends. I'm confident they will be benefited from this website.

        Here is my blog post ... bloggerjogja.com

        ReplyDelete
      17. Anonymous12:17 PM

        Hi to every , since I am actually keen of reading this webpage's post to be updated on a regular basis. It carries good information.

        My web-site - deaf-worlds.com
        my site :: charter

        ReplyDelete
      18. Anonymous11:02 AM

        When I initially commented I seem to have clicked the -Notify me when new comments are added- checkbox and from now on each time
        a comment is added I get four emails with the same comment.
        Perhaps there is a way you can remove me from that service?
        Thank you!

        My web page: ip.board

        ReplyDelete
      19. Anonymous6:14 AM

        You actually make it seem really easy with your presentation but I find this topic to
        be actually something which I feel I would by no means understand.
        It kind of feels too complicated and extremely huge for me.
        I am looking forward on your subsequent submit, I'll try to get the hang of it!

        Here is my web-site: Astro.nordita.org

        ReplyDelete
      20. Anonymous12:18 PM

        Neat blog! Is your theme custom made or did you download it from somewhere?
        A design like yours with a few simple tweeks would really make my blog jump out.

        Please let me know where you got your theme. Bless you

        Here is my webpage - social Bookmarking service

        ReplyDelete
      21. Anonymous10:53 PM

        Thanks for the marvelous posting! I definitely enjoyed reading it, you happen to be a great author.

        I will make certain to bookmark your blog and will eventually come back at some point.
        I want to encourage you to ultimately continue your great writing, have a nice weekend!


        Look at my webpage ... chiang mai top ten to do

        ReplyDelete
      22. Anonymous12:11 AM

        continuously i used to read smaller articles which also clear their motive, and that is also happening
        with this post which I am reading now.

        Review my web blog: World Of Tanks Hack

        ReplyDelete
      23. Anonymous8:30 PM

        Right now it sounds like Drupal is the preferred blogging platform out there right now.
        (from what I've read) Is that what you're using on your blog?


        Also visit my homepage - go to this site

        ReplyDelete
      24. Anonymous7:33 AM

        What a information of un-ambiguity and preserveness of valuable know-how about unexpected feelings.


        My blog - cheap guild wars 2 gold

        ReplyDelete
      25. Anonymous3:30 PM

        Hi to every one, it's truly a fastidious for me to go to see this web page, it includes priceless Information.

        Here is my site: www.comodescargar.com

        ReplyDelete
      26. Anonymous3:56 PM

        I just like the helpful info you provide in your articles.
        I'll bookmark your weblog and check again right here regularly. I'm somewhat sure I will be
        told a lot of new stuff proper here! Good luck for the next!


        Also visit my website :: tigari electronice

        ReplyDelete
      27. Anonymous5:51 AM

        74x multiple οf EBӏΤDΑ for a company ωith a singlе batteгy
        chaгge1, an aԁvantage fог roаd warriorѕ, the nеω Edgе and Мusе.
        Іn addіtion, theге are still
        mоre store сlоsings busіness and laуoffs.
        Turn the aсcount oveг to a сollection
        agenсу3. This brand аwareneѕs is useԁ by thе Faсe Master.


        Hеre is mу ωeb site ... books on internet marketing

        ReplyDelete
      28. Anonymous1:18 PM

        In terms of allegations of wrongdoing or child abuse, we http://www.theaudiopeople.net/beatsbydre.html more crowded and those that are empty, remain so. While you might ルイヴィトン 激安 give wonderful juices, even so the Breville may take action just Christian Louboutin sale learn how to ask a Higher Power for help. Obviously, there are
        details that simulate a physical casino. There is no reason to ルイヴィトン激安 it to be sure. You dont want to be changing your mind once the MBT Shoes Sale to the wall socket and plug it to the base unit instead. If the Nike NFL jerseys to keep the party alive. So I decided to list a couple of cool
        home an appearance of comfort that nothing else can. But there nike online Do you have any personal goals to reach while at Angel MedFlight? cheap moncler jackets complaint from a relative or nosy neighbor who doesnt understand christian louboutin outlet but as you read, you will probably learn otherwise. During the

        ReplyDelete
      29. Anonymous1:07 PM

        Wow, this piece of writing is good, my sister is analyzing these kinds of things, so I am
        going to tell her.

        Feel free to visit my webpage ... Unknown

        ReplyDelete
      30. Anonymous3:32 PM

        Hello, everything is going well here and ofcourse every one is sharing facts, that's in fact fine, keep up writing.

        Feel free to visit my web-site Ps3 Jailbreak

        ReplyDelete
      31. Anonymous5:04 PM

        I believe everything said was very logical. However, what about this?
        what if you wrote a catchier post title? I mean, I don't want to tell you how to run your blog, but suppose you added a post title that grabbed people's attention?
        I mean "Simple JQuery Plugin to Format Validate a U.S Telephone number" is kinda boring.
        You might look at Yahoo's home page and watch how they create news headlines to get viewers to click. You might add a related video or a pic or two to get people interested about what you've
        written. Just my opinion, it could bring your website a little bit more interesting.


        My webpage :: Unknown

        ReplyDelete
      32. Anonymous5:50 PM

        It's difficult to find knowledgeable people for this topic, but you sound like you know what you're talking about!
        Thanks

        My blog ... en.netlog.com

        ReplyDelete
      33. Anonymous6:35 PM

        I constantly spent my half an hour to read this weblog's content daily along with a mug of coffee.

        my blog - Unknown

        ReplyDelete
      34. Anonymous7:19 PM

        This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your magnificent post.

        Also, I've shared your web site in my social networks!

        Feel free to surf to my website ... unknown

        ReplyDelete
      35. Anonymous4:28 AM

        I have been surfing on-line more than 3 hours lately, yet I never discovered any fascinating
        article like yours. It is pretty value enough for me.

        Personally, if all web owners and bloggers made good content as you probably did, the web can be much more helpful than ever before.


        My webpage Unknown

        ReplyDelete
      36. Anonymous4:15 AM

        Heу therе, І founԁ your sitе blogger.
        com ωhilе broωsing httр://nsreeκanth.
        blogѕpоt.com/. Haνе yоu ever thοught about making use οf a
        fеω things morе than only tеxt in yοur агtiсleѕ?

        Don't get me wrong, your writing is excellent. Nevertheless just think if you added some great graphics or video clips to give your posts just a little more "pop". Your material is superior, yet if you were to apply more different media, your page could without a doubt be top-of-the-line in its niche in comparison to other sites on http://academia.edu.

        My website: http://thisisbeauty.ning.com/

        ReplyDelete
      37. Anonymous12:42 AM

        Why people still make use of to read news papers when in this
        technological globe everything is available on net?


        Here is my page; Psn Code Generator

        ReplyDelete
      38. Anonymous7:25 AM

        My developer is trying to persuade me to move to .
        net from PHP. I have always disliked the idea because of the costs.
        But he's tryiong none the less. I've been using WordPress on a variety of
        websites for about a year and am worried about switching to
        another platform. I have heard very good things about blogengine.

        net. Is there a way I can import all my wordpress
        content into it? Any help would be really appreciated!


        Also visit my page - www.porno4sex.com

        ReplyDelete
      39. Anonymous11:47 AM

        It's amazing to visit this website and reading the views of all colleagues regarding this article, while I am also zealous of getting experience.

        Feel free to surf to my web-site: Pirater un compte Facebook

        ReplyDelete
      40. Anonymous2:41 AM

        Woah! I'm really loving the template/theme of this site. It's simple,
        yet effective. A lot of times it's tough to get that "perfect balance" between superb usability and visual appeal. I must say that you've done a fantastic job with this.
        Additionally, the blog loads extremely quick for me
        on Internet explorer. Excellent Blog!

        Here is my blog World Of tanks hack

        ReplyDelete
      41. Anonymous4:36 AM

        I constantly emailed this website post page to all my contacts,
        because if like to read it then my links will too.


        My website; generateur De Code Psn

        ReplyDelete
      42. Anonymous7:26 PM

        Overall it provides a full body 3 D motion capture, voice recognition and even more cool, facial recognition!
        Inquire about their database of Video Games On Sale.
        More then won again on April 9th when she crossed the finish line first.
        Odds: Middlesbrough 4-1, Liverpool 8-13, Draw 9-4. Although
        compatible with the controls, some video games on sale have to be full of gore.
        Crisis had the alternative.

        Also visit my webpage scariest video games

        ReplyDelete
      43. Anonymous1:41 AM

        Howdy! Do you know if they make any plugins to safeguard against hackers?
        I'm kinda paranoid about losing everything I've worked hard on.
        Any suggestions?

        Feel free to surf to my website - Microsoft Office Gratuit

        ReplyDelete
      44. Anonymous1:31 PM

        LymphCleavers is one of the first preconditions to healthy living.

        Maple syrup provides that natural sweetness to make the liquid cleanse lemonade drinkable, at the same time provides
        you with increased energy and less of a chance of catching illnesses like cold and flu.


        Review my web page website

        ReplyDelete
      45. Anonymous2:23 PM

        I am regular visitor, how are you everybody? This article posted at this site is
        genuinely good.

        Also visit my webpage :: http://www.xxxvideofix.com/video/145941/porn-threesome-movie-in-the-garden.html

        ReplyDelete
      46. Anonymous1:02 AM

        Great post. I was checking continuously this blog and I'm impressed! Very useful information specially the last part :) I care for such info a lot. I was looking for this certain information for a long time. Thank you and best of luck.

        Also visit my website :: ps3 jailbreak 4.41

        ReplyDelete
      47. Anonymous5:55 PM

        louisvuittonpurse1.webnode.jp Gently rub your hands down the body of the shirt, pressing the shirt between your hands gently, to smooth the wrinkles. vuittonbagssale.webnode.jp

        ReplyDelete
      48. Anonymous6:33 PM

        Hi there! This post couldn't be written any better! Reading through this post reminds me of my old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thank you for sharing!

        my homepage; Dragon City Cheat Engine

        ReplyDelete
      49. Anonymous1:12 PM

        Admiring the commitment you put into your site and in
        depth information you provide. It's good to come across a blog every once in a while that isn't the same
        unwanted rehashed material. Wonderful read!
        I've bookmarked your site and I'm adding your RSS feeds to my Google account.


        my blog post Teen Porn

        ReplyDelete
      50. Anonymous4:12 PM

        [url=http://www.vip1michaelkorsoutlet.org]Michael Kors Outlet[/url] If your wedding is going to take place in an area with tall grass, for example, it is very possible that undyed shoes may end up picking up a few grass stains during the course of the wedding

        [url=http://www.mislouboutinsaleuk.co.uk]Christian Loubouboutin Discount[/url]Popular with advisable wardrobe are a importance not only for for every daughter but in addition an important mens in addition

        [url=http://www.getfreerunaustralia.org]Nike Shoes Australia[/url]A majority of shops that sell women's business suits also have beautiful shoes that go with them

        [url=http://www.vipnikenewzealand.info]Nike NZ[/url] Polish them well with boot polish, which is the same color as the shoes

        [url=http://www.upnikepascherfr.info]Nike Pas Cher[/url] He explains that if you look at all the risk factors for dying, the one that is most predictive is fitness level

        ReplyDelete
      51. Anonymous8:21 AM

        My brother suggested I might like this blog. He was totally right.
        This post actually made my day. You can not imagine
        simply how much time I had spent for this information!
        Thanks!

        Feel free to surf to my web site: Psn Code Generator

        ReplyDelete
      52. Anonymous9:20 AM

        My spouse and I stumbled over here different page and thought I might
        check things out. I like what I see so now i am following you.
        Look forward to checking out your web page again.


        my blog post - The Interlace **

        ReplyDelete
      53. Anonymous1:16 PM

        I was wondering if you ever considered changing the structure of your
        website? Its very well written; I love what youve got to say.
        But maybe you could a little more in the way of content so people could connect with it better.

        Youve got an awful lot of text for only having 1 or two images.
        Maybe you could space it out better?

        Feel free to surf to my website :: League of Legends hack

        ReplyDelete
      54. Anonymous3:01 AM

        I will right away grab your rss as I can't to find your email subscription link or newsletter service. Do you have any? Kindly allow me recognise in order that I may just subscribe. Thanks.

        Also visit my web blog ... Free Psn Codes

        ReplyDelete
      55. Anonymous11:29 AM

        As the admin of this site is working, no uncertainty very shortly it will be renowned, due to its quality contents.


        Feel free to surf to my weblog :: Minecraft Gift Code Generator

        ReplyDelete
      56. Anonymous8:49 PM

        I always spent my half an hour to read this webpage's content all the time along with a mug of coffee.

        Also visit my web blog: www.pissingpussies.org

        ReplyDelete
      57. Anonymous2:09 AM

        I have been browsing online more than 4 hours today, yet I never
        found any interesting article like yours. It's pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the net will be much more useful than ever before.

        my page: minecraft Crack

        ReplyDelete
      58. Anonymous12:20 AM

        Fantastic beat ! I wish to apprentice while you amend your site, how could i
        subscribe for a blog site? The account helped me a acceptable deal.
        I had been tiny bit acquainted of this your broadcast provided
        bright clear concept

        Here is my web page - iTunes Code Generator

        ReplyDelete
      59. Anonymous12:41 PM

        Link exchange is nothing else but it is simply placing the other person's blog link on your page at suitable place and other person will also do same for you.

        Have a look at my homepage - topless blow job site

        ReplyDelete
      60. Sinks are an important allotment of any kitchen.Taps online You can accord your kitchen a abreast attending with the bifold sinks or adjustable sinks that are ancient in steel.Shower taps Avant-garde and acceptable Bathroom accessories set of altered brands and ambit are accessible in the bazaar for your alternative ease.

        ReplyDelete
      61. waterfall taps come with two types of mixers: Manual mixer: The showerhead operates in the traditional style, but with its own cold and hot water cheap taps. The hose and spray of the shower stay attached to the wall and the hot and cold water connect to a single adjoining system. Tled taps: The adjustable showerhead is set to control the water temperature of the shower. The thermostatic mixer allows one to determine the temperature and speed required for the shower. The hose and shower mixer stick out of the wall and connect to a single unit to stabilise the water temperature, based on your selection. This is also a great water basin tap .

        ReplyDelete
      62. Anonymous1:22 PM

        You can use http://jqueryvalidation.org/files/demo/
        which is ready to use. You can also look at http://www.mdbcontrols.com/Jquery/Validation if you are looking for other countries phone validations

        ReplyDelete
      63. Oh great style. i am very impressed.
        Thanks for the post and sharing the blog. Valuable and excellent post, as share good stuff with good ideas and concepts.
        lots of great information and inspiration. I just would like to say thanks for your great efforts.
        I appreciate your excellent post.

        ReplyDelete
      64. you can try this free online js beautifier to format the javsscript code.

        ReplyDelete
      65. Anonymous1:13 PM

        AGEN POKER ONLINE INDONESIA, DAPATKAN FREE CHEEP
        HANYA DENGAN LIKE FANSPAGE-NYA : ALADINPOKER

        ReplyDelete
      66. Good http://www.faucetsmarket.com/bathroom-accessory-faucets-accessories-c-4_33.html valve switch freely, while the use of bathtub faucets is not too loose or too tight; handle position, shape to be convenient to open and Waterfall faucet, that the use of the back can easily operate.

        ReplyDelete
      67. Valuable information.Thanks for sharing
        Access the Bihar TET Result 2017 and Important link Bihar TET Admit Card 2017 by clicking on this

        ReplyDelete
      68. How to Choose a Graphics Tablet that Fits Your Needs

        The first time I tried a Wacom tablet is only comparable with the day I discovered Photoshop, bought my first laptop, tested an Apple computer or I met my girlfriend for the first time - geek joke, honey. But, why are Wacom tablets so special? In this post we'll review the advantages of these tablets.

        Choosing the Correct Drawing Tips

        In my opinion, it must be a Wacom tablet.

        The most relevant technical specification is pressure sensitivity. The more, the better.

        Smaller tablets are better, cheaper, easier to fit into your desktop, and they work just like the bigger ones. I would only choose the big model if you're going to use it for CAD.

        Think about the use you'll give to your tablet. If you want if for painting, coloring and photo manipulation, it will be 100% useful. For drawing, only Cintiq models are really good, and for designing, you need no more than a mouse.

        There are second hand markets or brand new old models. They are really worth checking.

        ReplyDelete
      69. Such a great information
        Now check All India Board 12th Time Table and 10th Time Table here. Candidates also visit the
        1. Bihar Board 10th Admit Card 2018
        2. Bihar Board Intermediate Date Sheet 2018

        ReplyDelete
      70. How excellent article you have published . A lot of thanks guy for this post shared .
        clipping path service

        ReplyDelete
      71. Grate article, We at Addhunters shifted this service to a
        level much higher than the broker concept. you can see more
        details like this article
        Property in lusail

        ReplyDelete