Tuesday, 6 January 2015

ASCII and JavaScript validations


Client side JavaScript validations are mostly done using regular expressions, but Regular expressions are difficult to understand. That is why, a complicated custom validations requires a lot of work to do. The easiest way in such case is to use ASCII Unicode characters and JavaScript. 

Every character has an alternate ASCII representation e.g.  ASCII code for Uppercase A is 65 and that for Z is 90. So we can say a character is an upper case alphabet If its ASCII code is between 64 and 91.

JavaScript code to find ASCII Unicode for a character is

              var ch = "H";
              var n = ch.charCodeAt(0);

it will return 72, because ASCII code for H is 72.

Now if for some input we want to have at least one uppercase character. we can write something like this.

      var str = document.getElementById('elementId').value;
      var condition = false;
      for( var i = 0;  i  <  str.length;  i++ )
      {
               var n = str.charCodeAt(i);
               if(n   >=   65 && n  <=  90)
               {
                      Condition = true;
                      Return;
               }
       }


Similarly we can do for special characters, numbers and small alphabets. e.g. we can do a check for special character @ as follow.

              if (n == 64)  // Unicode for @ is 64
              {
                    Condition = true;
                    Return;
              }


2 comments:

  1. It is a very nice, precise and to the point article. It saved me a lot of time. Waiting for more useful articles regarding javascript. Thank you so much.

    ReplyDelete