Custom validation from my own library

edited October 2011 in Modules
Another silly question probably but I'd like to check whether a unique field already exists in the DB with my own library:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Database_tools { public function __construct() { } public function is_not_existing_unique_field($value, $table, $column) { $this->CI = &get_instance(); $this->CI->db->select($column); $this->CI->db->from($table); $this->CI->db->where($column, strtolower($value)); $this->CI->db->limit(1); $query = $this->CI->db->get(); if($query->num_rows() == 0) { return true; } return false; } }

And this is what I'm doing in my function:
$this->validator->add_rule('email', 'is_not_existing_unique_field', 'That e-mail address is already registered by someone else', array($_POST['email'], 'msa_students', 'student_email'));

But it always returns false. I think it's not even loading my function.

Now I can see that the Validator library loads its own helper and off course those functions all work, is that the way to go?
I'd rather avoid doing DB stuff in helpers since the guys from CI always advised against that.

So is there any way to access my library functions inside add_rule()?
This is all front-end related.
Thanks again for your help :)

Comments

  • edited 4:25PM
    When add a rule that is a method on an object, you need to use an array syntax like so:
    $this->validator->add_rule('email', array($my_obj => 'is_not_existing_unique_field'), 'That e-mail address is already registered by someone else', array($_POST['email'], 'msa_students', 'student_email'));
    The key is the instance of the object, and the value is the method to call. If the method exists on the current object, then you use "$this".

    Also, it may not be relevant to how you have things setup, but there is a unique_fields property you can set on your model that will automatically check for unique values in the database upon save.
    http://www.getfuelcms.com/user_guide/libraries/my_model
Sign In or Register to comment.