How to use Kohana 3 validation (with forms) 2


For example:
1.1 Callback to check that either field 1 or field 2 is set (source):
public function _check_competition_formats(Validation $validation,$field) {
$check = $validation->as_array();
$forms = array_key_exists('forms', $check);
$sparring = array_key_exists('sparring', $check);
if ( ! ($forms OR $sparring)) {
$array->add_error($field, 'no_competition_formats');
}
}

1.2 Callback which checks multiple fields (source):
public function check_birthday(Validation $array, $field) {
if (isset($array['birthday_day']) AND isset($array['birthday_month'])AND isset($array['birthday_year'])) {
// Create the birthday as a UNIX timestamp
$this->birthday = mktime(0, 0, 0, $array['birthday_month'],$array['birthday_day'], $array['birthday_year']);
}
}

Retrieving and customizing error messages

Validation can be done for both models (on save) and various other forms. Because of this the messages are stored in separate, reusable files. You should put your message files under /application/messages/filename.php.
The files look like this:
array(
'username' => array(
   'username_available' => 'This username is already...',
   'not_empty' => 'Username must not be empty.',
   'invalid' => 'Password or username is incorrect.',
),
'password' => array(
   'matches' => 'The password and password confirmation ..',
   'range' => ':field must be within the range of :param1 to :param2',
),
);

Each field is a sub-array and each rule has it’s own field. Note that you can use :field to specify the field name.
To retrieve the messages, use $validate->errors($file) where $file is the filename (no extension).
The return value looks something like:
array(
   'password' => 'password must be less than 42 characters long',
   'password_confirm' => 'The password and password confirmation are different.',
   'username' => 'This username is already registered, please choose another one.',
   'email' => 'This email address is already in use.');

The simplest way to show these is the just print them in as a list. However, I will show one way to show these messages in context on the actual form.

0 comments:

Post a Comment