Wednesday, May 14, 2008

Check/Validate a date string in Javascript


I was looking for a simple Javascript function to check or validate a date string and most of the examples I have come across are too verbose. So I came up with a simple function that uses Regular Expressions and the built-in Date class.
//Checks if a given date string is in 
// one of the valid formats:
// a) M/D/YYYY format
// b) M-D-YYYY format
// c) M.D.YYYY format
// d) M_D_YYYY format
function isDate(s)
{   
  // make sure it is in the expected format
  if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
     return false;

  // remove other separators that are not valid with the Date class    
  s = s.replace(/[\-|\.|_]/g, "/"); 

  // convert it into a date instance
  var dt = new Date(Date.parse(s));     

  // check the components of the date
  // since Date instance automatically rolls over each component
  var arrDateParts = s.split("/");
     return (
         dt.getMonth() == arrDateParts[0]-1 &&
         dt.getDate() == arrDateParts[1] &&
         dt.getFullYear() == arrDateParts[2]
     );   
}
 
// test function to test the isDate function
function test_isDate()
{
  var arrDates = [ 
   '05/15/2008', '05-15-2008', 
   '05.15.2008', '05_15_2008',
   '15/15/2008', '05/35/2008',
   '05/15/1908', '15-15-2008',
   'a/1b/2008', '05/30/a008' ];
  for (var d in arrDates) 
     document.writeln("isDate('" + arrDates[d] + "') : " + isDate(arrDates[d]) + "");
} 
By the way, I am using a Javascript utility called SyntaxHighlighter, to render this code. If you have not already used this utility, I would highly recommend you check it out.

The code is self explanatory and when you run the test function, you get the following results:

Hope you find this useful. Please let me know if you come across any other elegant and efficient ways to check if a given string is a valid date or not using Javascript.

Happy coding,
Sonny

Quickly see Document and Window properties using Javascript

In my last post View dynamically generated HTML, I talked about how you can add a button to your Links toolbar in IE and link it to a snippet of Javascript code.

Here are a couple of snippets that I use to examine the current document properties and window properties. I have added them as "Show Doc Props" and "Show Win Props" buttons to my IE Links toolbar and they come very handy while debugging my web pages. These can also be used to look at all the different properties of document/window instance of any website that you visit:

Snippet for "Show Doc Props"
javascript:var dprop_=new Function("propName","try{return document[propName];}catch(err){return '<span style=color:red;>'+err.description+'</span>';}");var tbl="<table border='1' style='font-family:Tahoma;'>";for(var p in document)tbl+="<tr><td style='color:blue;'>"+p+"</td><td> "+dprop_([p])+"</td></tr>";tbl+="</table>";window.open("").document.write(tbl);


Snippet for "Show Win Props"
javascript:var wprop_=new Function("propName","try{return window[propName];}catch(err){return '<span style=color:red;>'+err.description+'</span>';}");var tbl="<table border='1' style='font-family:Tahoma;'>";for(var p in window)tbl+="<tr><td style='color:blue;'>"+p+"</td><td> "+wprop_([p])+"</td></tr>";tbl+="</table>";window.open("").document.write(tbl);

As you can see, this technique of linking code snippets to a button in your IE toolbar is a great way to access some general purpose Javascript utilities. One thing that I can think of is to have different set of snippets to automatically fill-in different form data. I understand that IE provides the abilitiy to save form data, but I do not like that feature plus it is not very flexible. For example, what if you want to use a different set of data based on the form or web page you are on? You could definitely use this technique for that purpose.

Hope you find this useful. Happy Scripting,


Sonny

Monday, May 12, 2008

View dynamically generated HTML in IE


Have you ever wanted to see the dynamically generated HTML of a page? If you use AJAX or lot of Javascript, I am sure you have added HTML content to your page on the fly and you wanted to see the active HTML source of that page, since IE only shows the original HTML source.

Perhaps you already know about how to do this, but, I often use this little Javascript code snippet to see the active content of a page and it really comes handy while developing web pages that use lot of Javascript to dynamically add content:

javascript:
window.open("").document.open("text/plain", "").write(document.documentElement.outerHTML);

I simply type this in the address bar and viola, I have the current HTML source of the page popped up in a new browser window. Better yet, I created a bookmark link using this snippet and every time I need to see the active HTML source of a page, I just click on this link.

Here are the steps to add a bookmark link for this Javascript snippet:
  1. In IE, press Ctrl+D to bring up "Add a Favorite" dialog
  2. Give it a name, something like "View Active Source"
  3. Use Links folder to create in and OK the dialog
  4. Have the Links toolbar displayed in your browser if it is not already
  5. Right-click on the "View Active Source" button > Properties
  6. In the "Web Document" tab, type the above line "javascript:..." in the URL box and OK the "View Active Source Properties" dialog
  7. Click "Yes" to the following warning message:
    The protocol "javascript" does not have a registered program. Do you want to keep this target anyway?
  8. Now, click on the button "View Active Source" in the Links toolbar and now you should be able to see the active HTML of the current page in a new window
There are few gotchas that you should be aware of as listed below. Use this snippet at your own risk and be warned that getting same Javascript code to consistently work across multiple versions of IEs is like peeling onions:
  1. As my title indicates, I have only tested this in IE and do not know if it works in other browsers or not. On that thought, other browsers might already provide this functionality and I remember hearing from a friend that Firefox does
  2. It won't work if Popup Blocker is turned on
Hope you find this useful and if you know any other cool ways to see the active HTML content of the page, please let me know.

Thanks for visiting my blog.


Sonny

Friday, May 9, 2008

Convert an integer to an ascii character in Javascript #2


In my previous post titled Convert an integer to an ascii character in Javascript, I said, I could not find any built-in methods in Javascript to convert a char into an integer and vice versa, well, it turns out that I have not looked hard enough. There are two methods on (one static and one instance as expected) String class that would do this conversion and these method are available since Javascript 1.2. I am sorry about the overlook. Here are sample functions to illustrate how these methods can be used in your code.

// Converts an integer (unicode value) to a char
function itoa(i)
{
   return String.fromCharCode(i);
}


// Converts a char into to an integer (unicode value)
function atoi(a)
{
   return a.charCodeAt();
}

Thanks,


Sonny

Wednesday, May 7, 2008

Convert an integer to an ascii character in Javascript


See my 2nd post for the revised code using built-in Javascript methods.

I was looking for a function to convert an integer into an ascii character in Javascript and could not find one. This is because Javascript does not support explicit character types, and to Javascript character is nothing but a string of length 1. This is what I have come up with. First, you define a string constant consists of all the ascii-7 characters. For non-printable characters you simply use a "?":

//reference: http://www.asciitable.com/
var asciiTable =
// 0 thru 9
"??????????" +
// 10 thru 19
"??????????" +
// 20 thru 29
"??????????" +
// 30 thru 39
"?? !\"#$%&'" +
// 40 thru 49
"()*+,-./01" +
// 50 thru 59
"23456789:;" +
// 60 thru 69
"<=>?@ABCDE" +
// 70 thru 79
"FGHIJKLMNO" +
// 80 thru 89
"PQRSTUVWXY" +
// 90 thru 99
"Z[\\]^_`abc" +
// 100 thru 109
"defghijklm" +
// 110 thru 119
"nopqrstuvw" +
// 120 thru 127
"xyz{|}~?";

Then you could have a function like this:
function itoa(i)
{
   return asciiTable.substr(i, 1);
}

Similarly, for printable characters you can have a function like this to convert character into an integer:
function atoi(c)
{
   return asciiTable.indexOf(c);
}

Hope you find this useful, and please let me know if you know any other elegant or efficient ways to do this in Javascript.

Good scripting,

Sonny