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.
Callbacks. These are not discussed in detail in the docs, but their purpose is to offer much more powerful tools: multiple fields can be accessed and modified at the same time. To add a callback:
Validation::factory($array)
->add_callbacks('birthday_year', array($this, 'check_birthday'));
Validation callbacks always take two parameters: function (Validate $array, $field) where $array is the current Validation class

0 comments:

Post a Comment