Welcome Guest, Not a member yet? Register   Sign In
Validation class: protection of a callback function
#1

[eluser]hbr[/eluser]
hi everyone,

As I was reading the documentation, I found the trick about making a function private by prefixing it with an underscore (in the controllers section).

But when defining a callback function in a validation process such as the one described in the doc, I noticed it was impossible to protect a validation method and prevent calling it from the url, here is what I mean :

- let's say we have a sign up controller called Signup
- a validation rule $validation["username"] = "required|callback_MyCallback" ; defined in index() { }
- a function called MyCallback($username) { }

If I type in the url http://localhost/mysite/signup/MyCallback/ , this will show an sql error, which means it tried to execute the function

If I rename MyCallback into _MyCallback, the validation rule will no longer work.

I thought about defining another function and make it private like "_username_process" and call it from within MyCallback. But I don't find this method clean.


Any idea ?
#2

[eluser]wiredesignz[/eluser]
Did you try a double underscore `callback__mycallback`?
#3

[eluser]hbr[/eluser]
yes, I tried that, and when I try to submit my form with an used username, it shows this error : "Unable to access an error message corresponding to your field name. "


and here is my function :

Code:
function _valid_username($username) {
        $sql = "SELECT COUNT(*) AS nb FROM `" . TABLE_PREFIX . "members` WHERE username=" . $this->db->escape($username) ;
        $query = $this->db->query($sql);
        $row = $query->row() ;
        
        if ($row->nb > 0) {
            $this->validation->set_message("valid_username", "This username is not available!");
            return false;
        }
        
        return true ;
    }




quite simple, isn't it? I think I didn't miss any case to set my error message for. So I don't understand why it shows that error.
#4

[eluser]wiredesignz[/eluser]
Code:
//don't forget the underscore for _valid_username
$this->validation->set_message("_valid_username", "This username is not available!");

This example may help
Code:
//validation rule
required|callback__is_unique[username]

function _is_unique($value, $field)
{
    $this->validation->set_message('_is_unique', "The %s {$value} is not available.");
    return (bool)(!$this->users->findBy("{$field} = '{$value}'"));
}
#5

[eluser]hbr[/eluser]
aaah that's the one I missed.

I was also wondering how to define a callback out of the controller and I just saw you signature :p
So i'll give it a try later.

Thanks a lot wiredesignz.




Theme © iAndrew 2016 - Forum software by © MyBB