2

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
0

2 Answers 2

4

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.