Skip to content

Instantly share code, notes, and snippets.

@chrisjacob
Created July 13, 2011 07:41
Show Gist options
  • Save chrisjacob/1079892 to your computer and use it in GitHub Desktop.
Save chrisjacob/1079892 to your computer and use it in GitHub Desktop.
Date Of Birth (DOB) Validation - PHP & JS pulled from a project - these snippets have not been tested on their own.
<script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="/js/jquery.validate.additional.js"></script>
<style>
li.error, label.error, p.error{color:#F00;}
#entryForm ol{list-style-type:none;}
#entryForm label{display:block; margin-top:6px;}
#entryForm label.error{margin-top:0px;}
</style>
<form action="submit.php" method="POST" id="entryForm">
<div id="entryFormError" <?php if(!isset($_GET['errors'])){ print 'style="display:none;"'; }?>>
<p class="error">There was an error with your entry:</p>
<?php
if(isset($_GET['errors']) && is_array($_GET['errors']) && !empty($_GET['errors']))
{
print '<ol>';
foreach($_GET['errors'] as $tErrorMessage)
{
print '<li class="error">' . $tErrorMessage . '</li>';
}
print '</ol>';
}
?>
</div>
<ol>
<li>
<label for="entryDay">
DATE OF BIRTH:
</label>
<div class="select">
<select id="entryDay" name="entry[day]">
<?php
$tDay = (isset($_GET['day'])) ? $_GET['day'] : '';
$tSelected = (empty($tDay)) ? 'selected="selected"' : '';
printf('<option %s value="" label="Day">Day</option>', $tSelected);
for($i=1; $i <= 31; $i++)
{
$tFormated = str_pad($i, 2, 0, STR_PAD_LEFT);
$tSelected = ($tDay == $tFormated ) ? 'selected="selected"' : '';
printf('<option %s value="%2$s" label="%2$s">%2$s</option>', $tSelected, $tFormated);
}
?>
</select>
<select id="entryMonth" name="entry[month]">
<?php
$tMonth = (isset($_GET['month'])) ? $_GET['month'] : '';
$tSelected = (empty($tMonth)) ? 'selected="selected"' : '';
printf('<option %s value="" label="Month">Month</option>', $tSelected);
$tMonths = array(
'Jan' => '01',
'Feb' => '02',
'Mar' => '03',
'Apr' => '04',
'May' => '05',
'Jun' => '06',
'Jul' => '07',
'Aug' => '08',
'Sep' => '09',
'Oct' => '10',
'Nov' => '11',
'Dec' => '12'
);
foreach($tMonths as $tKey => $tValue)
{
$tSelected = ($tMonth == $tValue ) ? 'selected="selected"' : '';
printf('<option %s value="%2$s" label="%3$s">%3$s</option>', $tSelected, $tValue, $tKey);
}
?>
</select>
<select id="entryYear" name="entry[year]">
<?php
$tYear = (isset($_GET['year'])) ? $_GET['year'] : '';
$tSelected = (empty($tYear)) ? 'selected="selected"' : '';
printf('<option %s value="" label="Year">Year</option>', $tSelected);
// 1993 will turn 17 in 2010
for($i=1900; $i <= 1993; $i++)
{
$tSelected = ($tYear == $i ) ? 'selected="selected"' : '';
printf('<option %s value="%2$s" label="%2$s">%2$s</option>', $tSelected, $i);
}
?>
</select>
</div>
</li>
<li>
<button type="submit" id="btnSubmit">ENTER</button>
</li>
</ol>
</form>
<script type="text/javascript">
jQuery(function($){
var validator = $("#entryForm").validate({
rules: {
"entry[year]": { required:true, checkdate:'#entryYear #entryMonth #entryDay' }
},
"entry[year]": { required:'Your date of birth is required', checkdate:'Please enter a valid date of birth' }
}
});
});
</script>
// Checkdate - Validate a Gregorian date, from an ISO formatted date string (YYYY-MM-DD) - as per PHP function checkdate()
// @param can pass in either:
// bool TRUE to validate a single field
// OR
// a string of 3 DOM ID's in the sequence Year, Month, Day e.g. #form_user_dob_year #form_user_dob_month #form_user_dob_day
// Note: only assign the validation rule to 1 of the 3 fields. e.g "user[dob][Year]": { required:true, checkdate:'#form_user_dob_year #form_user_dob_month #form_user_dob_day' },
jQuery.validator.addMethod("checkdate", function(value, element, param) {
// if validating 3 fields, replace the validating 'value' with the 3 field values, in ISO format YYYY-MM-DD
if(param && param !== true)
{
var paramArray = param.split(' ');
var pYear = $(paramArray[0]).val();
var pMonth = $(paramArray[1]).val();
var pDay = $(paramArray[2]).val();
value = pYear + '-' + pMonth + '-' + pDay;
}
// validate against jquery validator's dateISO: check
// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
var validDate = /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
if(validDate)
{
var dateArray = value.split('-');
var year = dateArray[0];
var month = dateArray[1];
var day = dateArray[2];
// PHP.js checkdate validation
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Pyerre
// * example 1: checkdate(12, 31, 2000);
// * returns 1: true
// * example 2: checkdate(2, 29, 2001);
// * returns 2: false
// * example 3: checkdate(03, 31, 2008);
// * returns 3: true
// * example 4: checkdate(1, 390, 2000);
// * returns 4: false
var myDate = new Date();
myDate.setFullYear( year, (month - 1), day );
var success = month >= 1 && month <= 12 && year >= 1 && year <= 32767 && ((myDate.getMonth()+1) == month && day<32);
return this.optional(element) || success;
}
}, jQuery.validator.messages.checkdate);
<?php
// phpinfo();
/**** Init ****/
$tFilePath = rtrim(dirname($_SERVER["PHP_SELF"]), '/\\');
$tSiteUrl = $_SERVER["SERVER_NAME"];
$tCurrentUrl = 'http://' . $tSiteUrl . $tFilePath;
$tData = ( isset($_POST['entry']) ) ? $_POST['entry'] : FALSE;
/**** Validate Required Data ****/
// Return No Data Error
if(empty($tData) || !is_array($tData))
{
$tErrors['errors'][] = 'No data submitted';
triggerError( $tErrors );
}
// Validate Missing Required Fields
$tRequiredFields = array(
'day' => 'Your DOB day is required',
'month' => 'Your DOB month is required',
'year' => 'Your DOB year is required'
);
$tErrors = false;
foreach($tRequiredFields as $tKey => $tValue)
{
if( !isset($tData[$tKey]) || false === $tData[$tKey] || '' === $tData[$tKey] )
{
$tErrors['errors'][] = $tRequiredFields[$tKey];
}
}
// Return Missing Field Errors
if($tErrors)
{
triggerError( $tErrors );
}
/*** Validate Special Conditions for Data ***/
// Invalid DOB
$VALID_DATEISO = '/^\d{4}(?:-\d{1,2}){2}$/';
$tData['dob'] = $tData['year'] . '-' . $tData['month'] . '-' . $tData['day'];
// validate date format YYYY-MM-DD
if ( !preg_match($VALID_DATEISO, $tData['dob']) )
{
$tErrors['errors'][] = 'Please enter a valid date of birth';
}
else
{
// validate date is real (i.e. there are not 31 days in February)
$tDateArray = explode('-', $tData['dob']);
$tYear = (int)$tDateArray[0];
$tMonth = (int)$tDateArray[1];
$tDay = (int)$tDateArray[2];
// Validate a Gregorian date
if ( !checkdate($tMonth, $tDay, $tYear) )
{
$tErrors['errors'][] = 'Please enter a valid date for date of birth';
}
}
// Return Validation Errors
if($tErrors)
{
triggerError( $tErrors );
}
/**
* FUNCTIONS
**/
function redirectURL( $tURL )
{
header("location: $tURL");
exit;
}
function triggerError( $tErrors )
{
global $tCurrentUrl;
global $tData;
$tParams = http_build_query($tErrors);
$tParams .= '&' . http_build_query($tData);
$tURL = $tCurrentUrl . '/?' . $tParams;
redirectURL($tURL);
}
?>
@chrisjacob
Copy link
Author

^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment