Showing posts with label kohana 3 forms. Show all posts
Showing posts with label kohana 3 forms. Show all posts

How to use Kohana 3 validation (with forms) 3


Displaying validation errors in context on the form

Here is how we want to show the forms:
To accomplish this, I have created a new Appform helper which uses the Form class, but wraps it’s input with application-specific markup for errors.

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');
}
}

How to use Kohana 3 validation (with forms) 1


I recently did a mini-series on Kohana 3 authentication, including a sample implementation. Since I got a lot of nice comments, thanks and page views, I figure I’ll write about Kohana 3 validation as well.

Overview of Kohana 3 validation

Validation is done using the Validate class, or via ORM using $model->check(). It uses the messages functionality in KO3, which is a system for specifying validation messages for various forms (I will discuss this).
The steps in validating a form are:
  1. Initialize the Validation class, adding filters, rules and callbacks for all the expected fields.
  2. Call Validate->check() and check whether the validation succeeded.
  3. If the validation failed, call errors($file) to get the error messages.
  4. Display the validation errors in the correct context on the form.
The first steps are covered by existing documentation, so I will focus on the last two steps here.

Initializing the Validation class

Initialization is done by adding filters, rules and callbacks. I will just discuss callbacks and some example cases. For the details, see the unofficial wiki and the official KO3 documentation.
Filters. Filters are mainly used to pre-process fields (e.g. trim, str_replace). Any PHP function can be used.
Rules. The Validation class has a nice set of basic validation rules, including rules for email addresses, credit cards, URLs and regexps.