Monday, November 11, 2013

Client + Server Side Validation = New Love

Having to do some recent form validation I wanted to have a solution that worked both on the client and server side. I found it!

It comes from combining jQuery Validation Plugin and jQuery Validation PHP Plugin

Using both of these libraries I create one rule file and incorporate it for both client and server side validation. My recent rule file looks like the following.

<?php
    $validation_rules = array(
        'rules' => array(
            'timestamp' => array(
                'required' => true,
                'number' => true
            ),
            'full-name' => 'required',
            'address' => 'required',
            'city-state-zip' => 'required',
            'home-phone' => 'required',
            'email' => array(
                'required' => true,
                'email' => true
            ),
            'birthday' => array(
                'required' => true,
                'dateUS' => true
            )    
        ),
        'messages' => array(
            'timestamp' => array(
                'required' => 'Select a date.',
                'number' => 'The date selected is not valid.'
             ),
            'full-name' => 'Enter your full name.',
            'address' => 'Enter your address.',
            'city-state-zip' => 'Enter your city state and zip.',
            'home-phone' => 'Enter a phone number.',    
            'email' => array(
                'required' => 'Enter your email address',
                'email' => 'Enter a valid email address'
            ),
            'birthday' => array(
                'required' => 'Enter your birthday',
                'dateUS' => 'Enter a date in the format mm/dd/yyyy.' 
            )
        )
    );
?> 

Notice how I have dateUS. That is a custom validation rule I set up. Adding custom rules is really easy for both libraries.

I am using Twitter Bootstrap for my framework, and the following js helps jQuery validator work great on the client side.

var settings = $('#form').validate(<?php echo json_encode($validation_rules); ?>).settings;
$.extend(settings, {
    errorClass: 'help-block',
    highlight: function(element){
        $(element).closest('.control-group').addClass('error');
    },
    success: function(element){
        element.closest('.control-group').removeClass('error');
    }
});

My post to page now follows something along the following logic.

<?php 
    require_once 'rules.php'; 
    require_once 'validator.class.php'; 

    $oValidator = new Validator($validation_rules);

    $validated_data = $oValidator->validate($_POST);

    if (count($validated_data) == 0){
        echo 'no errors';
    }
    else{
        print_r($validated_data);
    }
?>

Wednesday, January 9, 2013

Detecting When Scrolling Stops

There isn't a scrollstop listening event, so how can you call a function when the browser stops scrolling? The trick is to use setTimeout() to a call a function and then clearing the timer every time the page scrolls. When the page finishes scrolling the timer will not be cleared the final time and the function will execute. Here is a sample fiddle.

var timer;     
$(window).scroll(function(e){
         clearTimeout(timer);
         $('#search_tab').fadeOut('slow');
         timer = setTimeout(checkStop,150);
 });

function checkStop(){
  $('#search_tab').fadeIn('slow');
} 

Friday, October 5, 2012

Reformat Text for Blog

I wrote this for my blog. I have my blog set up so that I need to change all of my opening and closing tags (< >) for html elements to their html entity name element (&lt; &gt;). This can be done with a few lines of javascript.

$(function(){
 $('#cleanFormat').click(function(){
     $('#text').val($('#text').val().replace(/</g,"&lt;")); 
     $('#text').val($('#text').val().replace(/>/g,"&gt;"));
 });
});

To see an example of this follow this link.

Creating a Datepicker

I had a project recently where I needed to create a custom datepicker for a HTML form. I will walk through the basics of how I was able to accomplish this.

The CSS

My specific form required the ability for the user to add multiple dates for a specific event up to a maximum of 20. So I knew I needed to hide the unneeded date fields from view. So I created the class hidden to allow for this. The datepicker needed an absolute positioning because I wanted to move it around the page as needed.

 .hidden{
  display:none; 
 }
 #datepicker{
  background: #ccc;
  position: absolute; 
  z-index: 50;
  border: 1px solid #000;
  padding: 5px;
 }
 #closeButton{
  float:right; 
 }

The Datepicker

I used select lists to allow the user to select the date and start time. The key here was using php to pull in the current year so that I could dynamically create it. I also used php to create some for loops so that I didn't have to manually go through and type all of the options I wanted in my select lists.

<div id="datepicker" class="hidden">
 <table border="0">
  <tr>
   <td colspan="3"><strong>Date:</strong></td>
  </tr>
  <tr>
   <td>
    <select class="changeDate" id="month" name="month">
     <option id="month1" value="1">January</option>
     <option id="month2" value="2">February</option>
     <!-- etc... -->
    </select>
   </td>
   <td>   
    <select class="changeDate" id="day" name="day">
     <?php
      for($i=1; $i<32; $i++){
         echo '<option id="day'.$i.'" value="'.$i.'">'.$i.'</option>'; 
      }
     ?>
    </select>
   </td>
   <td> 
    <select class="changeDate" id="year" name="year">
     <option selected="selected" value="<?php echo date(Y); ?>"><?php echo date(Y); ?></option>
     <option value="<?php echo date(Y) + 1; ?>"><?php echo date(Y) + 1; ?></option>
     <option value="<?php echo date(Y) + 2; ?>"><?php echo date(Y) + 2; ?></option>
     <option value="<?php echo date(Y) + 3; ?>"><?php echo date(Y) + 3; ?></option>
     <option value="<?php echo date(Y) + 4; ?>"><?php echo date(Y) + 4; ?></option>
    </select>
   </td>
  </tr>
 </table>  
 <table border="0">
  <tr>
   <td colspan="3"><strong>Start Time:</strong></td>
  </tr>
  <tr>
   <td>
    <select class="changeDate" id="hour" name="hour">
     <?php
      for($i=1; $i<13; $i++){
         echo '<option id="hour'.$i.'" value="'.$i.'">'.$i.'</option>'; 
      }
     ?>
     </select>
    </td>
    <td>
     <select class="changeDate" id="minute" name="minute">
      <option id="minute00" value="00">00</option>
      <option id="minute01" value="01">01</option>
      <option id="minute02" value="02">02</option>
      <!-- etc... up to ten -->
      <?php
       for($i=10; $i<60; $i++){
         echo '<option id="minute'.$i.'" value="'.$i.'">'.$i.'</option>'; 
       }
      ?>
     </select>
    </td>
    <td>
     <select class="changeDate" id="ampm" name="ampm">
      <option id="am" value="am">am</option>
      <option id="pm" value="pm">pm</option>
     </select>
    </td>
   </tr>
  </table>   
 <input id="closeButton" type="button" value="Close"/>
</div>

The Javascript

I have condensed my code to just the basics. Please see comments for more specifics.


 $(function(){
   var globalFocus = 'required-date'; //I used this to see which date field was currently in focus
                
   $('#month<?php echo date(n);?>').attr('selected', 'selected');
   $('#day<?php echo date(j);?>').attr('selected', 'selected');
   $('#hour<?php echo date(g);?>').attr('selected', 'selected');
   $('#minute<?php echo date(i);?>').attr('selected', 'selected');
   $('#<?php echo date(a);?>').attr('selected', 'selected');
   //I used the above code to set up the defaults for the datepicker
   updateDate(globalFocus);//This sets the focused date field value
    
   $('.date').focus(function() { //corresponds to all of the date fields 
         globalFocus = $(this).attr('id');
         $('#datepicker').show();
         var position = $(this).position(); //Return position of date field to position the date picker right below it
         var height = $(this).height(); 
         $('#datepicker').css('top', position.top+height); 
         $('#datepicker').css('left', position.left);
  });

  $('.changeDate').change(function(){
        updateDate(globalFocus);
  });
  
  $('#closeButton').click(function(){
        $('#datepicker').hide();
  });
 });

 function updateDate(currentFocus){
     $('#'+currentFocus).val($('#month').val()+'/'+$('#day').val()+'/'+$('#year').val()+" "+$('#hour').val()+':'+$('#minute').val()+$('#ampm').val()+" - "+$('#hourend').val()+':'+$('#minuteend').val()+$('#ampmend').val());
 }

Thursday, June 14, 2012

jQuery Mobile Select Menu

Had a bit of a headache today trying to figure out how to dynamically load a select menu using ajax with jQuery Mobile. The select menu would load fine, but I was losing all of the styling. Thanks to a post from kadaj's musing I realized that I needed to initialize the select menu before I tried to refresh it.

$('#selectMenu').selectmenu();
$('#selectMenu').selectmenu('refresh', true);

This method helped me avoid the "Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'" error I was getting.