Created
August 16, 2012 18:18
-
-
Save chadhutchins/3372336 to your computer and use it in GitHub Desktop.
FuelPHP Form Validation - Require field if another field is set and/or another field has a certain value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
required_if Custom Validation Method | |
// Example 1 - require field if another field has been set | |
// Require the Billing State field if Billing Country has a value | |
$val = Validation::forge(); | |
$val->add_callable('customvalidation'); | |
$val->add_field('billing_country', 'Billing Country','required'); | |
$val->add_field('billing_state', 'Billing State','required_if[billing_country]'); | |
// Example 2 - require field if another field has a specific value | |
// Require the Billing State field if Billing Country equals "US" | |
$val = Validation::forge(); | |
$val->add_callable('customvalidation'); | |
$val->add_field('billing_country', 'Billing Country','required'); | |
$val->add_field('billing_state', 'Billing State','required_if[billing_country,US]'); | |
*/ | |
class Customvalidation | |
{ | |
public static function _validation_required_if($value,$check_field=null,$check_value=null) | |
{ | |
// grab the active validation | |
$validation = Validation::active(); | |
if (!empty($validation)) | |
{ | |
$validation->set_message('required_if', ':label is required.'); | |
// check_field is required | |
if (empty($check_field)) | |
{ | |
return false; | |
} | |
// get the value of the check_field | |
$field_value = $validation->validated($check_field); | |
if (empty($check_value)) | |
{ | |
// if check_value is empty, return whether or not field_value has a value | |
return !(!empty($field_value) && empty($value)); | |
} | |
else | |
{ | |
// else, check if field_value equals the check_value | |
if (!empty($field_value) && $field_value==$check_value) | |
{ | |
// if field_value exists and its value equals the check_value, return true if value is not empty | |
return !empty($value); | |
} | |
else | |
{ | |
// since field_value is empty OR the field_value and check_value don't match, the field in question is not required | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment