Welcome Guest, Not a member yet? Register   Sign In
Validation for date
#1

[eluser]cinewbie81[/eluser]
I have 3 dropdowns item on my form which are :-

1) Date : 1-31
2) Month : 1-12
3) Year : 2005-2020 (Ok this can be any year actually)

How can i do the verification of the date in my controller class ??
For eg: 29 Feb 2009 is invalid, whereas 29 Feb 2008 is valid.. Any idea ?
#2

[eluser]xwero[/eluser]
Extend the validation library with this rule. I've added it to the MY_Validation wiki page if anyone wants to make make the method better.
Code:
function valid_date($str,$params)
{
   $explode = explode(',',$params);
   $month = $this->CI->input->post($explode[0]);
   $day = $this->CI->input->post($explode[1]);
   if(!day) // year and month don't need to be validated
   {
     return true;
   }
   if(is_numeric($str) && is_numeric($month) && is_numeric($day))
   {
      $max_days = date('t',mktime(0,0,0,$month,1,$str));
      if($day <= $may_days)
      {
         return true;
      }
   }
   return false;
}
You could also change it into a callback but i've seen others use the same approach entering dates.
To validate you add following rules
Code:
$rules['month'] = 'numeric';
$rules['day'] = 'numeric';
$rules['year'] = 'numeric|valid_date[month,day]';
#3

[eluser]Lone[/eluser]
This is one situation that I find something like a DatePicker to be very handy - and you can still allow for a dd/mm/yyyy input.
#4

[eluser]axle_foley00[/eluser]
I believe the php function checkdate() would come in handy at times like this.

http://docs.php.net/manual/en/function.checkdate.php

UPDATE
You could write your date validation function similar to the one that tobyberesford used on the CI wiki for his FormDate Class to do validations of your dates:

Code:
function valid_date()
{
    if (!checkdate($this->input->post('month'), $this->input->post('day'), $this->input->post('year')))
    {
        $this->validation->set_message('valid_date', 'The %s field is invalid.');
        return FALSE;
     }
}

As you can see, this simply uses the PHP native function checkdate().

Hope that helps.
#5

[eluser]xwero[/eluser]
Nice catch axle_foley00. i've changed the function on the MY_Validation page.
#6

[eluser]axle_foley00[/eluser]
xwero: ok cool.
#7

[eluser]marios[/eluser]
I use a date picker but it is still good to validate.
if you have just one field for your date that takes input like : 02/05/2007 or 02-05-2007 or any kind of date format i have created this validation :
( i have removed the validation message for simplicity.
date formating is based on php strftime.

for linux only:

Code:
function validdate($str,$format="%m/%d/%Y")
{
   $date_array = strptime($str, $format);
   if($date_array === false || date_array['unparsed'] != "")
   {
     return false;
   }
   else
   {
      return checkdate($date_array['tm_mon'],$date_array['tm_mday'],$date_array['tm_year']);
    }
}

since strptime is not implemented in windows you can use the following:
(which works on both linux and windows)

Code:
function validdate($str,$format="%m/%d/%Y")
{
   $date_array = $this->_strToTime($str, $format);
   if($date_array === false ||
      !isset($date_array['tm_mon']) ||
      !isset($date_array['tm_mday']) ||
      !isset($date_array['tm_year'])
     )
   {
     return false;
   }
   else
   {
      return checkdate($date_array['tm_mon'],$date_array['tm_mday'],$date_array['tm_year']);
    }
}

//borrowed and modified from php strptime page
function _strToTime($date, $format) {
        $search = array('%d', '%D', '%j', // day
        '%m', '%M', '%n', // month
        '%Y', '%y', // year
        '%G', '%g', '%H', '%h', // hour
        '%i', '%s');
        
        $replace = array('(\d{2})', '(\w{3})', '(\d{1,2})', //day
        '(\d{2})', '(\w{3})', '(\d{1,2})', // month
        '(\d{4})', '(\d{2})', // year
        '(\d{1,2})', '(\d{1,2})', '\d{2}', '\d{2}', // hour
        '(\d{2})', '(\d{2})');
        
        
        
        $return = array('s' => 'tm_sec',    // sec
                        'i' => 'tm_min',   //min
                        'g' => 'tm_hour', 'h' => 'tm_hour',   //hour
                        'd' => 'tm_mday', 'j' => 'tm_mday', //day
                        'm' => 'tm_mon',  'n' => 'tm_mon',  //month
                        'y' => 'tm_year');
        
        $pattern = str_replace($search, $replace, $format);
        
        
        if(!preg_match("#$pattern#", $date, $matches)) {
            return false;
        }
        $dp = $matches;

        if(!preg_match_all('#%(\w)#', $format, $matches)) {
            return false;
        }
        $id = $matches['1'];

        if(count($dp) != count($id)+1) {
            return false;
        }

        $ret = array();
        for($i=0, $j=count($id); $i<$j; $i++) {
            $ret[$return[strtolower($id[$i])]] = $dp[$i+1];
        }

        return $ret;
    }


usage example:
$field_rules['mydate']  = 'trim|required|validdate[%n/%j/%Y]


I hope this helps
#8

[eluser]mindprojects[/eluser]
I use this in my form helper and validation and i've found it usefull and simple:

Code:
/**
* valid_date
*
* check if a date is valid
*
* @access    public
* @param    string
* @param    string
* @return    boolean
*/

function valid_date($str,$format= 'dd/mm/yyyy')
{
        switch($format)
        {

            case 'yyyy/mm/dd':
                if(preg_match("/^(19\d\d|2\d\d\d)[\/|-](0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])$/", $str,$match) && checkdate($match[2],$match[3],$match[1]))
                {
                    return TRUE;
                }
            break;
            case 'mm/dd/yyyy':
                if(preg_match("/^(0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])[\/|-](19\d\d|2\d\d\d)$/", $str,$match) && checkdate($match[1],$match[2],$match[3]))
                {
                    return TRUE;
                }
            break;
            default: // 'dd/mm/yyyy'
                if(preg_match("/^(0?[1-9]|[12][0-9]|3[01])[\/|-](0?[1-9]|1[012])[\/|-](19\d\d|2\d\d\d)$/", $str,$match) && checkdate($match[2],$match[1],$match[3]))
                {
                return TRUE;
                }
            break;

        }
        return FALSE;
}
#9

[eluser]vitoco[/eluser]
Code:
function valid_date( $fecha )
{
    // VALID FORMAT = yyyy-mm-dd
    if (ereg ("([0-9]{4})-([0-9]{2})-([0-9]{2})", $fecha, $fecha_array))
    {
        // VALID DATE IN CALENDAR
        return ( checkdate($fecha_array[2],$fecha_array[3],$fecha_array[1]) )
            ? true
            : false ;
    }

    return false;
}
#10

[eluser]imarek[/eluser]
Took me some time to write it but this regex works perfect:
Code:
preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $str);
I am using it at: http://www.PromoSquare.com to validate date field with jquery




Theme © iAndrew 2016 - Forum software by © MyBB