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:
- Initialize the Validation class, adding filters, rules and callbacks for all the expected fields.
- Call Validate->check() and check whether the validation succeeded.
- If the validation failed, call errors($file) to get the error messages.
- 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
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.