Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

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>
      

      Thursday, September 23, 2010

      GWT and JQuery - my musings

      I have been programming with GWT and JQuery for about 8-10 months now. I started with GWT initially, and loved it (I was a POJD - Plain Old Java Developer till some time back). GWT is an amazing take on combining the powers of a Structured, Strictly Typed Java to the absolute power of the JavaScript. I really think the ideas of JSNI invocation and the seamless RPC interface is nothing more than wonderful. It makes a good Java Developer instantly productive on the Script based GUI. We predominantly had Java Developers and it made life so easy for them to be doing a Complex AJAX based front end in no time with GWT.

      Lately I made amends to my knowledge base on JavaScript and started using the JQuery Framework. It has gradually grown on me. Below is some of my thoughts on both of the frameworks. I agree that I am more influenced by JQuery and might be favoring usage of JQuery in most cases.

      1) JQuery is built upon a simple principle of "progressive improvement".
         - You start from a basic design and keep enhancing it. This approach is very productive as you start with a basic page design and then add functionality by using the selectors and defining the behaviors
        
      2) JQuery Code is simpler and easier to understand. We shrank some of our 10K line script files to just a 1K or so. Significant amount of modularity is achieved using the plugins.

      3) JQuery Supports encapsulation, though (I would say) imperfectly. All the plugin code can be thought as encapsulated. it is not in the strictest sense as you see with GWT (As it is written in Java), but I believe that JQuery enhances the JavaScript by providing a lot more scope for encapsulation.

      4) Service invocations: One of the biggest advantages I saw with the GWT was that making REST based calls to the Server became so easy. GWT-RPC makes those rally easy and straight forward, the only rider being the GWT needs a server piece to do it with GWT-RPC (Your Project is not all Script I mean). At least in some cases we had a bad taste with this as the Existing Server application was written on JDK 1.4, and to get RPC running we had to make it run on JDK 1.5. Do not think this is a big problem, it is high time we upgraded. JQuery provides a robust AJAX call framework, gives very good options of hooking up to most of the callbacks. One thing I am seeing is that as I use completely Script, the server side is decoupled of how I provide REST based services. This is not to say GWT is not capable of doing this, it can very well do the same using the HTTP Request Infrastructure. But rather than writing GWT RPC Services, we are now preferring to write our REST Services using JAX-RS or Grails, which decouples the Server side from what Scripting framework is used on the Client.

      5) JQuery has very good templating support now. Most templating engines are available as plugins and can be used out of the Box, with JSON data fed in to them. Makes life really simpler for complex objects presented on Repeating Divs, Grids etc.

      6) I found it kind of difficult to debug the generated code from GWT (Even in the detailed version). The Java debugger on Eclipse Helps, but my firebug or my server logs did not give me much of a clear picture when an RPC call failed. May be I am not smart enough for that. JQuery code was mine, debugging turns out to be simpler.

      7) Plugins for JQuery has increased many fold int eh last year, we could virtually find ready made functionality for whet ever crazy stuff we wanted to do, Grids, Grids within Grids, Slideshows, Graphs (Bar, Pie, Line -- what not ????)

      8) Editors : Google launched the GWT Designer recently which I believe should make a world of difference to the way the GWT pages are coded. This should make building the UI and even positioning of elements much more simpler with GWT. JQuery Visual elements being nothing more than HTML Markup, will always have advantage of using of any of the HTML WYSIWYG Editors out there.

      Conclusions :

      I definitely think both GWT and JQuery are really powerful tools. GWT might be the best choice for people coming from a Java background and want to still program with the Strongly Typed language with good compile time checking. But this requires a lot of unlearning of Java as well as to what cannot be used on the Client side code

      JQuery on the other hand, expects you to know HTML, DOM Structure and Event handling but is simpler as a framework. I strongly believe that unless you have a huge pool of Java (Only) Developers who need to be used for Web GUI development, all other cases it might be worthwhile to consider using JQuery instead.