JavaScript function to automatically add slashes to date

In converting an old Windows app to a browser app, the user wanted to be able to enter dates without the slashes. Here's a simple jscript:

   1: // Function to convert short date string (MMddyy)
   2: // or (MMddyyyy) to a date string (mm/dd/yyyy).
   3: // txtBox is the actual textbox control
   4: // with the value to be processed.
   5: function FixShortDate(txtBox) {
   6:     if (txtBox == null) { 
   7:         return '' }
   8:  
   9:     var re = new RegExp(/(\d{6})(\d{2})?/);
  10:  
  11:     if (re.test(txtBox.value))
  12:     {
  13:         if (txtBox.value.length == 8) {
  14:             txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/' + txtBox.value.substring(4, 8)
  15:         }
  16:         
  17:         if (txtBox.value.length == 6) {
  18:             if (txtBox.value.substring(4, 6) < 20)
  19:             {
  20:                 txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/20' + txtBox.value.substring(4, 6);
  21:             }
  22:             else
  23:             {
  24:                 txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/19' + txtBox.value.substring(4, 6);
  25:             }
  26:         }
  27:     }
  28:     return txtBox.value;
  29: }

I simply add the call to the onBlur event and we're off to the races.

   1: Enter your date:
   2: <input type="text" id="testdate" onblur="FixShortDate(this)" />

I've chosen 2020 as my cutoff year so anything 033120 will be 03/31/1920 while 033119 will be 03/31/2019.

Hope you enjoy.

Comments

Anonymous said…
Thank you!
I had the exact same request and your code came very handy.
Unknown said…
Dear,

Thanks a lot for sharing such nice code with us.... Thnx a lot....
Anonymous said…
helped me in coding......
Thank you.
Anonymous said…
Thank you! This helped me a lot!! :)
Anonymous said…
Nevada is the one state that has no significant restrictions towards slot machines each for public and private use. In New Jersey, slot machines are only allowed in lodge casinos operated in Atlantic City. Several states allow slot machines (as nicely as any casino-style gambling) only on 카지노사이트 licensed riverboats or completely anchored barges.

Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Windows 8 Keyboard Shortcuts

Get Asp.Net Profile properties from Sql