Table of Contents
StatusDraft
TodoAdd all methods, example form

Validation Library

You can validate any arbitrary array of data items, by defining filters, rules and custom callbacks to apply to the individual items.

If you're searching for some pre-made validation functions, check the validation helper.

Additional information: Article Tutorial

Getting started

Load the Library

The most common data array to validate is _POST. Data arrays may be merged and validated as one entity.

$post = new Validation($_POST);
// combine different arrays
$post = new Validation(array_merge($_POST, $_FILES));
// Using the factory
$post = Validation::factory($_POST)->add_rules('field_name', 'required');

Adding rules

After you instantiate the Validation object you can add rules to fields. Common rules such as required are defined by the library. The library is designed to work seamlessly with the valid helper.

Example: These are all equivalent:

$_POST->add_rules('email', 'required', array('valid','email'));
$_POST->add_rules('email', 'required', 'valid::email'); 
$_POST->add_rules('email', 'required', 'email');

All rules are callbacks to functions, the first rule 'required' tests whether the field is required. The second rule tests whether the email address is valid.

Adding filters

There are two kinds of filters, those processed before validation and those after. You can use filters to trim fields of spaces or uppercase them. Any function that accepts and returns a string can be used.

$_POST->pre_filter('trim','title');
$_POST->post_filter('ucfirst','title');

Adding callbacks

Besides rules you can also add your own callbacks. A callback is simply a method you define to do some custom check on a field. Pass the Validation object to the callback as an argument. The callback should add an error using the add_error() method if the custom checking fails.

It is important to understand that callbacks are ALWAYS processed after rules. Validation does NOT stop after a rule error is found. So your callback could be passed input that is invalid. You should ALWAYS place a test for rule errors in your callback, as per the example.

// Add the callback, we assume $post is the validation object and the callback is defined in the same controller, hence we use, $this
$post->add_callbacks('email', array($this, 'trigger_error'));
// Define the callback method
function trigger_error(Validation, $post)
{
   // Did we find any rule errors? if so, return immediately.
   if (array_key_exists('email', $post->errors())
       return;
 
   // OK, now it's safe to use the field input in our callback
   // Do something, user name query check, etc
 
   // Did we find any errors?, then add the error message to the field
   $post->add_error('email', 'email_error_triggered');
}

Validating

Validating is done with the validate() method. It first process the pre-filters, then the rules, callbacks and last the post_filters.

If it encounters any errors on an input field, it adds the field name as an array key to the Validation errors array.

If any error was found, boolean FALSE is returned. if there are no errors, returns TRUE.

if($_POST->validate())
{
   echo 'No validation errors found';
}
else
{
   echo 'Validation errors were found ';
   $errors = $_POST->errors();
   foreach ($errors as $key => $val)
   {
       echo $key.' failed rule '.$val.'<br />';
   }
}

Adding Errors

You can use method add_error() to add an error to the Validation error array.

$post->add_error( 'password', 'pwd_check');

Define Error Messages

Kohana does not define generic error messages for validation. Error messages should be defined in custom files, created in the application/i18n folder.

Example: application/i18n/en_US/my_form_errors.php A default error condition may be defined.

$lang = array
(
	'field' => Array
		(
			'required' => 'The name cannot be blank.',
			'alpha' => 'Only alphabetic characters are allowed.',
			'default' => 'Invalid Input.',
		),
);

Retrieve Error Messages

Error messages are retrieved with the errors() method. By default an array is returned, with the field name as key, and the defined rule as value.

To retrieve customized error messages, an error messages file must be passed to the errors() method.

$errors = $validation->errors();
// Assuming one rule defined, add_rules('field', 'required') $errors array contains ('field' => 'required')
//
// Fetch errors using an error messages file
$errors = $validation->errors('form_errors')
// Assuming a $lang array was created containing $lang = array('field' => array('required' => 'field may not be blank'))
// Then $errors will contain an array of ('field' => 'field may not be blank')

Retrieve Input Data

Validation input data is accessible via the as_array() method. This is very useful for re-populating form fields, for example:

// Assume form fields were previously defined in an array eg. $form = array('field_one' => '', 'field_two' => '')
// After validation, if errors occurred, we need to re-populate the previously entered information in the form fields.
// We use the array helper to overwrite the the original array
$form = arr::overwrite($form, $post->as_array());

Rules

Rules Specific to Validation Library

Rule Parameter Description Example
required No Returns FALSE if form field is empty
length Yes Returns FALSE if the field is too long or too short length[1,30] - between 1 and 30 characters long
or length[30] - exactly 30 characters long
depends_on Yes Returns FALSE if form field(s) defined in parameter are not filled in depends_on[field_name]
matches Yes Returns FALSE if field does not match field(s) in parameter matches[password_again]
chars Yes Returns FALSE if field contains characters not in the parameter chars[a,b,c,d,1,2,3,4]


Rules Made Available by Valid Helper

See valid helper for full descriptions and examples.

Rule Parameter Description Example
email No Returns FALSE if email is not valid
email_domain No Returns FALSE if domain of an email does not have valid MX record
email_rfc No Returns FALSE if email is not rfc822 valid
url No Returns FALSE if url is not valid
ip Optional Returns FALSE if ip is not valid
credit_card Yes Returns FALSE if credit card is not valid credit_card[mastercard]
phone Optional Returns FALSE if phone number is not a valid length phone[7,10,11,14] - either 7, 10, 11 or 14 digits long (default is 7, 10 and 11)
alpha_numeric Optional Returns FALSE if form field does not consist only of alphabetical or numeric characters
alpha_dash Optional Returns FALSE if form field does not consist only of alphabetical, numeric, underscore and dash characters
digit Optional Returns FALSE if form field does not consist only of digit characters
numeric No Returns FALSE if form field is not a valid number (positive, negative or decimal)
standard_text No Returns FALSE if form field is not valid text
(letters, numbers, whitespace, dashes, periods and underscores are allowed)
decimal Optional Returns FALSE if form field is not in proper decimal format
Optional parameter is for a specific decimal format
decimal - is any valid decimal format
decimal[4,2] - is 4 digits and 2 decimal places
libraries/validation.txt · Last modified: 2008/09/03 07:19 by avantar