| Project: | Validation API |
| Version: | 6.x-1.0-rc5 |
| Component: | Code |
| Category: | support request |
| Priority: | normal |
| Assigned: | Unassigned |
| Status: | active |
Issue Summary
I was having incredible difficulty getting a Validator to work with a Date module field . Apparently, the reason is because the current validator.module does not grab multiple values from a single form element (it does not treat the form element as an array).
This was easily fixed by adding a single line to the code around line 519 of validation_api.module ( $arrayvalue = $element['#value']; ) and then referencing this $arrayvalue instead of the documented $value in my Validator:
function _validation_api_run_validator($element, &$form_state, $validation_api_field, $validator) {
// Set the value depending on it's location
$value = (is_array($element['#value']) ? $element['#value']['value'] : $element['#value']);
$arrayvalue = $element['#value']; // custom code to allow referencing array values from the form fieldMy field was named field_birthday[0]. I added a Field under Validation API and created a Validator for it.
My Validator grabbed the year / month / day fields like so :
$dob_year = intval($arrayvalue['value'][year]);
$dob_month = intval($arrayvalue['value'][month]);
$dob_day = intval($arrayvalue['value'][day]);Below is my entire code, which validates a user's birth day and makes sure they are over 13 years old
$now = time();
$dob_year = intval($arrayvalue['value'][year]);
$dob_month = intval($arrayvalue['value'][month]);
$dob_day = intval($arrayvalue['value'][day]);
$year = intval(date('Y', $now));
$month = intval(date('m', $now));
$day = intval(date('d', $now));
# if the dob is more than 13 years before today's year, then return true
if (($year - $dob_year) > 13) {
return true;
}
# if the dob is 13 years before today's year, and this month is the dob month or earlier, and this day is the dob day or earlier, return true
if ( (($year - $dob_year) == 13) && (($month - $dob_month) >= 0) && (($day - $dob_day) >= 0) ) {
return true;
}
else
return false;Credits to Igashu_ on #drupal-support , irc.freenode.net , for this solution