WEBDOOD.COM

Tag: Javascript

BadAss Javascript Date Validator – Useful for Rails

by webdood on Jul.18, 2009, under Javascript, Ruby on Rails, Software Development

Should make a point of posting cool routines like the one below as they are useful to many.

I have seen quite a lot of good examples of folks using (and expanding upon) routines I wrote for some of the Gadgets that ship with Vista (to be found in library.js if you have a Vista Box) and for some of AOL’s (apparently deprecated) Mac OSX Widgets.

Functions like showOrHide, getLocalizedString, getSpinner (emulates Vista-like spinner image) I have seen in use all over the place.

Here is a somewhat badass Date Validator routine I wrote today that takes in either a string date value or an <INPUT> Element Object and validates the date to be formatted as DD-MM-YYYY.

I wrote it for use by a Ruby on Rails application, but it’s pretty handy as a general library function.

var DATE_REGEX  = /^(\d{2})-(\d{2})-(\d{4})$/
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// validateDate([object|string] oHTMLInputElement) - Validates a date value   //
// ===============================================                            //
//   You can pass in the id to an <input> Element, an actual               //
//   oHTMLInputElement or an actual date value in the form of a string        //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

function validateDate(oHTMLInputElementOrDateValue) {
  var theDateValueToValidate = "";
  var theValidatedDateValue = false;
  var bIsInputElement = false;
  if (typeof(oHTMLInputElementOrDateValue)=="string")  {
    var oHTMLInputElement = document.getElementById(oHTMLInputElementOrDateValue);
    if (oHTMLInputElement && typeof(oHTMLInputElement=="object") && (oHTMLInputElement.tagName=="INPUT")) {
      theDateValueToValidate = oHTMLInputElement.value;
      bIsInputElement = true;
    } else {
      // Presumably they just passed in a date string
      theDateValueToValidate = oHTMLInputElementOrDateValue;
      bIsInputElement = false;
    }
  } else {
    // They have passed in an Object
    if (typeof(oHTMLInputElementOrDateValue=="object") && (oHTMLInputElementOrDateValue.tagName=="INPUT")) {
      var oHTMLInputElement = oHTMLInputElementOrDateValue;
      theDateValueToValidate = oHTMLInputElement.value;
      bIsInputElement = true;
    }
  }

  // If we have a date value to actually validate, let's get started
  if (theDateValueToValidate != "") {
    var theDateValue = theDateValueToValidate.replace(/\//g,"-");  // Ruby-side only accepts hyphens
    if (DATE_REGEX.test(theDateValue)) {
      theValidatedDateValue = theDateValue;
    } else {
      if (theDateValue.indexOf('-') > -1) {
        var theMonth = theDateValue.split('-')[0];
        var theDay   = theDateValue.split('-')[1];
        var theYear  = theDateValue.split('-')[2];
        // If they've entered a single digit for either Day or Month, pad with zero accordingly
        theMonth = parseInt(theMonth).PadWithZero();
        theDay   = parseInt(theDay).PadWithZero();
        if (theYear.length==2) { theYear = "20" + theYear; }    // If they've entered a two-digit year, assume it's in the 21st century
        theDateValue = theMonth + "-" + theDay + "-" + theYear; // Rebuild the date. Hopefully this will work
        if (DATE_REGEX.test(theDateValue)) {
          theValidatedDateValue = theDateValue;
        }
      }

      // If we get to this point and none of our efforts have worked to format the date
      // as "required", throw an error (if they are using an INPUT element)
      if (!theValidatedDateValue && bIsInputElement) {
        alert("ERROR: Date must be formatted as follows:\n\n\tDD-MM-YYYY\n\nPlease correct before continuing");
        oHTMLInputElement.focus();
      }
    }
  }

  if (bIsInputElement && theValidatedDateValue) {
    oHTMLInputElement.value = theValidatedDateValue;
  }
  return theValidatedDateValue;
}

Hope you find this one useful as well.

Shannon Norrell

Now on GitHub as well

Leave a Comment :, , , more...

Fast JavaScript Max/Min on an Array Taking Arbitrary Number of Arguments

by webdood on Feb.25, 2009, under Javascript, Software Development

What's the fastest way to find the largest, or smallest, number in an array?

Array.max = function( array ){
  return Math.max.apply( Math, array );
};
Array.min = function( array ){
  return Math.min.apply( Math, array );
};

By using JavaScript's .apply() method on a built-in function you can pass in an array of unlimited arguments.

Shannon Norrell

Leave a Comment :, , more...

parseInt Bug in Firefox, IE6 and IE7 for values “08″ and “09″

by webdood on Mar.18, 2008, under Software Development

Quick Entry:

There is a bug in shipping versions of Internet Explorer and Firefox wherein if you attempt to use parseInt on a number with leading zeros, the value returned will be incorrect for “08″ and for “09″ due to the Javascript interpreter thinking these are, in fact, Octal numbers (and there being no “Octal” value greater than 7, the value returned is “0″).

Try it.  Copy/Paste the following Javascript into your browser’s url:

javascript:alert(parseInt(“08″))

Anyway, a somewhat esoteric bug perhaps but it did cause an infinite loop today when I was attempting to scan over a date range where the dates were stored with leading zeroes.

The fix?

USE parseFloat() instead.

Leave a Comment :, , , more...

fetchNVPValue – a routine to extract a value from a querystring

by webdood on Mar.11, 2008, under Javascript, Software Development

There are probably more efficient – and more bullet-proof – ways to do this, but figured I had better capture this before I forgot that I wrote it.

Shannon Norrell

////////////////////////////////////////////////////////////////////////////////
//
// fetchNVPValue( string aNVPName, string aURL )
//           Extracts the value of a Named Value Pair (NVP) from a URL
//       eg: fetchNVPValue( “name”, “http://mypage.com?id=123&name=Shannon&foo=bar” ) returns “Shannon”
//
////////////////////////////////////////////////////////////////////////////////
function fetchNVPValue( aNVPName, aURL ) {
  var retVal = “”;
  var bItsInThereSomeWhere = (aURL.toLowerCase().indexOf(aNVPName) > -1);
  // If we have a URL, a name to look for and it’s in there somewhere …
  if ( aNVPName && aURL && bItsInThereSomeWhere ) {
    var theURL = aURL.toLowerCase().replace(/\+/g, ‘ ‘);    // Turn all ‘+’ signs back into spaces, if applicable
    var args = theURL.split(“&”);
    for (var i=0;i<args.length;i++) {
      var nvp = args[i].split(“=”); // Break out each argument out into a NVP
      var name  = unescape(nvp[0]);
      if (name==aNVPName) {
        retVal = nvp[1];
        break;
      }
    }
  }
  // If we still haven’t extracted it and it’s in there somewhere, the Named value follows a “?” in the URL, rather than a &
  if (( retVal == “”) && bItsInThereSomeWhere) {
    if (aURL.toLowerCase().indexOf(“?” + aNVPName) > -1) {
      retVal = aURL.split(“?”)[1].split(“=”)[1];
    }
  }
  return retVal;
}

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org