Browse by Month RSS Feed
  • September 2010
  • August 2010
  • July 2010
  • May 2010
  • April 2010
  • March 2010

  • Form Tools 1.3.1 releasedAugust 30, 2006
    Filed under: Form Tools @ 7:09 pm

    Nothing terribly thrilling to report. This version just contains a few minor bugs that people have reported since the 1.3.0 release.

    As always, you can find out more from the website: www.formtools.org

    Comments (0)


    Function: html_dump()August 29, 2006
    Filed under: Code, PHP @ 10:22 pm

    This function isn't completed, but I'll add it here anyway. One of the primary reasons I'm using Wordpress to store my code is to facilitate tracking it down later. I'll return to this and polish it off at some point. Or someone else out there could do it for me...!

    /*----------------------------------------------------------------------------*\
      Function:   html_dump
      Abstract:   development helper tool to output PHP variables in HTML-friendly
                      formats. [written to emulate ColdFusion's <cfdump> tag.]
      Parameters: - $hash: the hash to display (e.g. $_POST)
                       - $label: a label for the outputted text.
                       - $hidden_onload: hides the displayed object by default
      Returns:    a string containing an HTML-rendering of the input variable.
     
      INCOMPLETE.
    \*----------------------------------------------------------------------------*/

    function html_dump($var, $label = "", $start_hidden = false)
    {
      // embedded function which determines if an array is a hash or not.
      function is_hash($var)
      {
        if (!is_array($var))
          return false;
     
        return array_keys($var) !== range(0,sizeof($var)-1);
      }

     
      $table_id = rand();         // create a unique ID for the displayed table
      $var_type = gettype($var)// determine what kind of variable we're displaying
      $html     = "";             // stores the HTML-ified variable

      // determine hide/show javascript enabling user to toggle visibility of
      // outputted variable contents.
      $js_hide = 'document.getElementById("html_dump_' . $table_id . '_show").style.display = "none";
                  document.getElementById("html_dump_'
    . $table_id . '_hide").style.display = "block";';
      $js_show = 'document.getElementById("html_dump_' . $table_id . '_show").style.display = "block";
                  document.getElementById("html_dump_'
    . $table_id . '_hide").style.display = "none";';

      // determine the CSS display attribute of the hidden & visible tables
      $start_hidden_cs = ($start_hidden) ? "" : "display: none";
      $start_show_cs   = ($start_hidden) ? "display: none" : "";
     
                 
      switch ($var_type)
      {
        case "array":

           // ------------------------------- HASH ----------------------------
           if (is_hash($var))
           {
             // styles for hash display
             $table_style  = "width: 100px; background-color: #efefef;";
             $label_style  = "background-color: #003300; font-family: arial; font-size: 8pt; color: white; font-weight: bold;";
             $key_style    = "background-color: #339933; color: white; font-family: arial; font-size: 8pt;";
             $value_style  = "background-color: white; color: black; font-family: arial; font-size: 8pt;";
             $button_style = "font-family: arial; font-size: 7pt;";

             // HIDDEN table
             $html .= "<table id='html_dump_{$table_id}_hide' cellpadding='1' cellspacing='1' style='$table_style; $start_hidden_cs;'>
                   <tr>
                     <td style='$label_style' nowrap>[ Hash ] $label</td>
                     <td style='$label_style'>                 
                       <input type='button' value='SHOW' style='$button_style' onclick='$js_show' />
                     </td>
                   </tr>
                   </table>"
    ;

             // VISIBLE table
             $html .= "
                 <table id='html_dump_{$table_id}_show' cellpadding='1' cellspacing='1' style='$table_style; $start_show_cs;'>
                 <tr>
                   <td style='$label_style' nowrap>[ Hash ] $label</td>
                   <td style='$label_style'>
                     <input type='button' value='HIDE' style='$button_style' onclick='$js_hide' />               
                   </td>
                 </tr>"
    ;

             foreach ($var as $key=>$val)
             {
               $html .= "<tr>
                       <td style='$key_style'>$key</td>
                       <td style='$value_style'>$val</td>
                     </tr>"
    ;
             }
             $html .= "</table>";
           }

           // ------------------------------- ARRAY ----------------------------
           else
           {
             $html .= "Array";
           }
           
           break;
      }
      return $html;
    }

    Comments (0)


    Function: String.reverse()August 29, 2006
    Filed under: Code, JavaScript @ 10:18 pm

    Prototype function to reverse the contents of a string.

    String.prototype.reverse = function()
    {
      var reversed = "";
      var i = this.length;
      while (i>0)
      {
        reversed += this.substring(i-1, i);
        i--;
      }
      return reversed;
    }

    Comments (2)


    Function: validateFields()August 29, 2006
    Filed under: Code, ColdFusion @ 10:01 pm
    <!-----------------------------------------------------------------------------------------------
      Function:  validateFields
      Purpose:   This function checks required fields for ANY webform. It takes two parameters:
                 pageAttributes - ALL form field info (attributes) received by post page
                 fieldInfo      - an array. Each index is a list of the form:
                    "requirement,fieldname[,fieldname2 [,fieldname3, date_flag]],error message".
                     fieldname2 is optional, and is only used for comparing one field to another.

                  alid "requirement" strings are:
                      "required"    - field must be filled in
                      "digits_only" - field must contain digits only
                      "length=X"    - field has to be X characters long
                      "length=X-Y"  - field has to be between X and Y (inclusive)
                                  characters long
                      "valid_email" - field has to be valid email address
                      "valid_date"  - field has to be a valid date
                                fieldname:  MONTH                 fieldname2: DAY
            fieldname3: YEAR
                                date_flag:  "later_date" / "any_date"
                      "same_as"     - fieldname is the same as fieldname2 (intended
                                for password comparison).
                      "range=X-Y"   - checks that a number has a value between
                                X and Y (inclusive).

        E.g. an area home phone number form field "<input type='text' name='homePhone_area' />" would be
        validated as follows:

          <cfset variables.fieldInfo = ArrayNew()>
          <cfset variables.fieldInfo[1] = "required,homePhone_area,Please enter area home phone">
          <cfset variables.fieldInfo[2] = "digits_only,homePhone_area,Home phone area must only contain digits">
          <cfset variables.fieldInfo[3] = "length=3,homePhone_area,Home phone area must be 3 digits long">

          <cfinvoke   
           component="#request.componentPath#.Error"
           method="validateFields">

            <cfinvokeargument name="pageAttributes" value="#attributes#">
            <cfinvokeargument name="fieldInfo" value="#variables.fieldInfo#">
          </cfinvoke>

        Notes:
        - The array position in which the error messages appear for a single form field IS important. If
        homePhone_area failed the first check (index 1), the function will NOT check the two following
        requirements (indexes 2 and 3). That way, the user won't get three error messages for one incorrectly
        filled in field.
        - Duplicate error messages are not returned.

        If any of the the form fields contain an error, the function redirects the user back to the original form
        and makes two new variables available in sessions in WDDX format:

          session.wddx_pageAttributes
          session.wddx_errorMessages

        So, form page should contain this code, where-ever you want the list of error messages to
        appear:
       
          <!--- if required, display form validation errors --->
          <cfif IsDefined("session.wddx_errorMessages")>
            <cfwddx action="wddx2cfml" input="#session.wddx_errorMessages#" output="variables.errMessages">
            <cfinvoke
             component="#request.componentPath#.Error"
             method="displayErrors">

              <cfinvokeargument name="errorMessages" value="#variables.errMessages#">
            </cfinvoke>
          </cfif>

        NOTES FOR UPGRADES:
          - consider adding "zip_canada", "zip_US", "zip_northAmerica" options.
          - I deliberately return a struct of "fieldname" => "error message", not just error messages,
            so you could use the fieldname data to HIGHLIGHT those fields that contain errors.
          - "is_alpha" requirement
          - add valid_date routine, which checks for valid dates - plus additional later_date,
            earlier_date options to check date being inputted is earlier or later than current date.
      ---------------------------------------------------------------------------------------------->
      <cffunction access="public" name="validateFields" output="true" displayName="validateFields"
        hint="Validates fields for any web form; returns a list of error messages">

        <cfargument name="pageAttributes" type="any" required="yes" displayname="pageAttributes">
        <cfargument name="fieldInfo" type="array" required="yes" default="" displayname="reqFieldInfo">

    <!--- this stores a LIST of errors found. (An array of lists of form: 'fieldName,error message' --->
        <cfset variables.errors = ArrayNew(1)>    <!--- stores all errors --->

        <cfloop from="1" to="#ArrayLen(arguments.fieldInfo)#" index="i">

          <!--- split the required field information into its component parts --->
          <cfset variables.requirement  = ListFirst(arguments.fieldInfo[i], ",")>
          <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>
          <cfset variables.fieldName    = ListFirst(arguments.fieldInfo[i], ",")>
          <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>

          <!--- if we're doing a "same_as" validation, there's a second fieldname listed --->
          <cfif variables.requirement EQ "same_as">     
            <cfset variables.fieldName2   = ListFirst(arguments.fieldInfo[i], ",")>
            <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>

          <!--- if we're doing a "valid_date" validation, extract extra fields --->
          <cfelseif variables.requirement EQ "valid_date">
            <cfset variables.fieldName2   = ListFirst(arguments.fieldInfo[i], ",")>
            <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>
            <cfset variables.fieldName3   = ListFirst(arguments.fieldInfo[i], ",")>
            <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>
            <cfset variables.date_flag    = ListFirst(arguments.fieldInfo[i], ",")>
            <cfset arguments.fieldInfo[i] = ListDeleteAt(arguments.fieldInfo[i], 1, ",")>       
          </cfif>

          <!--- at this point, the error messsage is all that's left --->
          <cfset variables.errorMessage    = arguments.fieldInfo[i]>

         
          <!--- IF this field doesn't have an error already associated with it, error-check it --->
          <cfset variables.errorFound = false>
          <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
            <cfif ListContains(variables.errors[i], fieldName)>
              <cfset variables.errorFound = true>
            </cfif>
          </cfloop>

          <cfif NOT errorFound>
            <!--- if the requirement is LENGTH, rename requirement to "length" for switch statement --->
            <cfif Find("length=", variables.requirement)>
              <cfset variables.lengthRequirements = variables.requirement>
              <cfset variables.requirement = "length">
            </cfif>
           
            <!--- if the requirement is RANGE, rename requirement to "range" for switch statement --->
            <cfif Find("range=", variables.requirement)>
              <cfset variables.rangeRequirements = variables.requirement>
              <cfset variables.requirement = "range">
            </cfif>

           
            <!--- verify the field passes the required test --->
            <cfswitch expression="#variables.requirement#">

              <cfcase value="required">
                <cfif NOT StructKeyExists(arguments.pageAttributes, variables.fieldName) OR
                  arguments.pageAttributes[variables.fieldName] EQ "">

                  <!--- if this error message isn't already contained in "errors", add it --->
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                      <cfset variables.errorAlreadyExists = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>

                </cfif>
              </cfcase>

              <cfcase value="digits_only">
                <cfif REFind("[^[:digit:]]", arguments.pageAttributes[variables.fieldName])>
                 
                  <!--- if this error message isn't already contained in "errors", add it --->
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage)>
                      <cfset variables.errorAlreadyExists = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>

                </cfif>
              </cfcase>

              <cfcase value="length">
                <cfset variables.lengthRequirements = Replace(variables.lengthRequirements, "length=", "")>
                <cfset variables.lengths            = ListToArray(variables.lengthRequirements, "-")>
       
                <cfif ArrayLen(variables.lengths) IS 2>

                  <!--- check field length is between specified length range --->
                  <cfif (Len(arguments.pageAttributes[variables.fieldName]) LT variables.lengths[1]) OR
                      (Len(arguments.pageAttributes[variables.fieldName]) GT variables.lengths[2])>

                    <!--- if this error message isn't already contained in "errors", add it --->
                    <cfset variables.errorAlreadyExists = false>
                    <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                      <cfif ListContains(variables.errors[i], variables.errorMessage)>
                        <cfset variables.errorAlreadyExists = true>
                      </cfif>
                    </cfloop>
                    <cfif NOT variables.errorAlreadyExists>
                      <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                    </cfif>
     
                  </cfif>
               
                <cfelse>
                  <!--- otherwise, the user wants the field contents to be a specific length --->
                  <cfif Len(arguments.pageAttributes[fieldName]) NEQ variables.lengths[1]>

                    <!--- if this error message isn't already contained in "errors", add it --->
                    <cfset variables.errorAlreadyExists = false>
                    <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                      <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                        <cfset variables.errorAlreadyExists = true>
                      </cfif>
                    </cfloop>
                    <cfif NOT variables.errorAlreadyExists>
                      <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                    </cfif>

                  </cfif>             
                </cfif>
              </cfcase>
             
              <cfcase value="valid_email">
                <cfif NOT REFindNoCase("^['_a-z0-9-]+(\.['_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name))$", arguments.pageAttributes[fieldName])>

                  <!--- if this error message isn't already contained in "errors", add it --->
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                      <cfset variables.errorAlreadyExists = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>

                </cfif>
              </cfcase>

              <cfcase value="valid_date">
             
                <!--- included for future extensibility --->
                <cfif variables.date_flag EQ "later_date">
                  <cfset variables.isLaterDate = true>
                <cfelse>
                  <cfset variables.isLaterDate = false>             
                </cfif>

                <cfinvoke
                 component="#request.componentPath#.Error"
                 method="isValidDate"
                 returnvariable="variables.isValid">

                  <cfinvokeargument name="date_month" value="#arguments.pageAttributes[variables.fieldName]#"/>
                  <cfinvokeargument name="date_day" value="#arguments.pageAttributes[variables.fieldName2]#"/>
                  <cfinvokeargument name="date_year" value="#arguments.pageAttributes[variables.fieldName3]#"/>
                  <cfinvokeargument name="isLaterDate" value="#variables.isLaterDate#"/>
                </cfinvoke>

                <!--- if this error message isn't already contained in "errors", add it --->
                <cfif NOT variables.isValid>
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                      <cfset variables.errorAlreadyExists = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>
                </cfif>
              </cfcase>

              <cfcase value="same_as">
                <cfif arguments.pageAttributes[fieldName] NEQ arguments.pageAttributes[fieldName2]>

                  <!--- if this error message isn't already contained in "errors", add it --->
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                      <cfset variables.errorAlreadyExists = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>

                </cfif>
              </cfcase>

              <cfcase value="range">
                <cfset variables.rangeRequirements  = Replace(variables.rangeRequirements, "range=", "")>
                <cfset variables.range              = ListToArray(variables.rangeRequirements, "-")>   

                <!--- check field value is between specified number range ---> 
                <cfif (arguments.pageAttributes[variables.fieldName] LT variables.range[1]) OR
                    (arguments.pageAttributes[variables.fieldName] GT variables.range[2])>

                  <!--- if this error message isn't already contained in "errors", add it --->
                  <cfset variables.errorAlreadyExists = false>
                  <cfloop from="1" to="#ArrayLen(variables.errors)#" index="i">
                    <cfif ListContains(variables.errors[i], variables.errorMessage) NEQ 0>
                      <cfset variables.errorFound = true>
                    </cfif>
                  </cfloop>
                  <cfif NOT variables.errorAlreadyExists>
                    <cfset ArrayAppend(variables.errors, variables.fieldName & "," & variables.errorMessage)>
                  </cfif>

                </cfif>
              </cfcase>

              <cfdefaultcase>
                Unknown requirement in Error.validateFields: <b>#variables.requirement#</b>
                <cfabort>
              </cfdefaultcase>
            </cfswitch>

          </cfif>
        </cfloop>

        <!--- if there are validation errors, return attribute contents and error messages to referer page --->
        <cfif NOT ArrayIsEmpty(variables.errors)>

          <!--- convert the error message array into a wddx string in order to send it to form page --->
          <cfwddx action="cfml2wddx" input="#variables.errors#" output="variables.wddx_errorMessages" usetimezoneinfo="no">
          <cfwddx action="cfml2wddx" input="#arguments.pageAttributes#" output="variables.wddx_pageAttributes" usetimezoneinfo="no">

          <!--- store this information in a (temporary) session, then redirect. Note:
                this session info is destroyed once the user fills in the form correctly. --->
         
          <cflock scope="session" type="Exclusive" timeout="20" throwontimeout="yes">
            <cfset session.wddx_errorMessages  = variables.wddx_errorMessages>
            <cfset session.wddx_pageAttributes = variables.wddx_pageAttributes>
          </cflock>

          <cflocation url="#CGI.HTTP_REFERER#" addtoken="no">
        </cfif>
      </cffunction>

    Comments (0)


    Function: Array.sort()August 29, 2006
    Filed under: Code, JavaScript @ 9:56 pm

    This one-liner sorts a numerical javascript array.

    // replace ARRAY_NAME with the name of your array.
    ARRAY_NAME.sort(function(a,b) { return a-b; });

    Comments (0)


    Function: Array.is_equal_to()August 29, 2006
    Filed under: Code, JavaScript @ 9:54 pm

    This function compares two arrays, returning true or false depending on the contents.

    Array.prototype.is_equal_to = function(arr)
    {
      if (this.length != arr.length)
        return false;

      for (var i = 0; i <arr.length; i++)
      {
        if (this[i].is_equal_to)
        {
          if (!this[i].is_equal_to(arr[i]))
            return false;
          else
            continue;
        }
        if (this[i] != arr[i])
          return false;
      }
      return true;
    }

    Comments (0)

    Next Page »