开发者

Codeigniter return validation error from helper

I'm making a URL validation helper which I set as a rule in my form validation.

$this->form_validation->set_rules('link_url', 'Link URL', 'trim|required|xss_clean|max_length[255]|validate_url');

If the validate_url returns FALSE how can I return a custom validation error from the helper?

Helper

if ( ! function_exists('validate_url'))
{
    function validate_url($str)
    {
       $pattern = "/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(开发者_如何转开发?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
        if (!preg_match($pattern, $str))
        {
            $this->form_validation->set_message('validate_url', 'URL is not valid');
            return FALSE;
        }
        else 
        {
            return TRUE;
        }
    }
}

When I submit the form I get

Fatal error: Using $this when not in object context


As @alex mentioned you are trying to call an object within a function, any way you can avoid this error by using get_instance() which returns super object. I am not sure if you can use this helper function as callback inside form_validation lib though.

here is the code:

if ( ! function_exists('validate_url'))
{
    function validate_url($str)
    {
        $ci = get_instance();

       $pattern = "/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
        if (!preg_match($pattern, $str))
        {
            $ci->form_validation->set_message('validate_url', 'URL is not valid');
            return FALSE;
        }
        else 
        {
            return TRUE;
        }
    }
}


You are creating a global function, not a method of an object.

In that context, $this doesn't point to any instantiated object. To set messages on an object, you'd need to change $this to the validation object.

You could be able to replace the body of that function with return (bool) parse_url($str).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜