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
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 callbacks always take two parameters: function (Validate $array, $field) where $array is the current Validation class
0 comments:
Post a Comment