Validating Input Data with the CodeIgniter PHP Framework - Adding validation capabilities to the generic model class
(Page 3 of 4 )
In reality, the implementation of the previously mentioned “validate()” method is much simpler than you might think, since it utilizes some native classes provided by CodeIgniter to do its business. Do you remember that the model’s constructor grabs an instance of the CI super object? Well, in doing so it’s possible to use these native classes in a pretty straightforward manner within any custom library.
But it’s time to get rid of the theory and see how the “validate()” method looks. So, here it is:
/**
* Validates model input data
*
* @author Alejandro Gervasio
* @return Boolean TRUE on success - FALSE on failure
* @access protected
*/
protected function validate()
{
// If no validation rules or no model were provided data set appropriate error
if (count($this->validation) === 0)
{
$this->errors[] = 'No validation rules were set for the model.';
return FALSE;
}
// Loads CI validation library
$this->ci->load->library('validation');
// Load CI language file for validation
$this->ci->lang->load('validation');
// resets error messages
$this->errors = array();
foreach ($this->validation as $field => $rules)
{
$expRules = explode('|', $rules);
// if the field is not required check next one
if (! in_array('required', $expRules, TRUE))
{
continue;
}
// Iterates through the validation rules
foreach ($expRules as $rule)
{
// Removes the parameter from the rule (when specified)
$param = FALSE;
if (preg_match("/(.*?)[(.*?)]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Calls the validation method that corresponds to the rule
As explained before, the “validate()” method checks to see if each element of the $data property fits the validation rules specified for it. To perform this task without “reinventing the wheel,” it uses the CodeIgniter validation and language classes respectively, as you can see clearly above. In addition, it’s important to note that if there is not a method of the validation class that verifies the inputted data, then a native PHP function will be used for this purpose instead. Of course, this section borrows much of the logic implemented by the native validation class of CodeIgniter, so in this case I have to give the corresponding credits to its development team.
Finally, the method will return TRUE or FALSE depending on the result of the validation process, and any eventual errors will be stored in the $errors array for further displaying. That was not too hard to grasp, right?
So far, so good. At this stage I’m pretty sure that you understand how the “validate()” method does its thing. Thus, it’s time to see how the model class will look after including the signature corresponding to the method in question. This topic will be the conclusion of this article, so all that you have to do is click on the link below and read the section to come.