Codeigniter add custom youtube link validation rule to your form

Before you start, you will need to have basic codeigniter form validation basic for this post. If you don’t, you may take a look at codeigniter documentation.


STEP 1  Form input

Create a text input field named youtube_link

<input type="text" name="youtube_link" value="">


STEP 2  Add a callback function

After the standard validation, add a new callback function to the rule.

$this->form_validation->set_rules('youtube_link', 'Youtube Link', 'required|xss_clean|trim|callback_validate_youtube');


STEP 3 Create the validation function

Create a new public function in your controller. Please take note that the function name should not include “callback”.

public function validate_youtube($str){
    preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<[^&\n]+#", $str, $matches);
    if(!isset($matches[0])){ //if validation not passed
        $this->form_validation->set_message('validate_youtube', 'Invalid <b>youtube link</b>.');
        return FALSE;
    }else{ //if validation passed
        return TRUE;

You can easily replace the preg_match pattern that suits your need.


Unable to access an error message corresponding to your field name.

One of the mistake I made the first time when I tried to create a new custom validation is, when I set message for the error, I put the input name instead of the function name. And there’s when I get this error message.



$this->form_validation->set_message('youtube_link', 'Invalid <b>youtube link</b>.');



$this->form_validation->set_message('validate_youtube', 'Invalid <b>youtube link</b>.');




Give us some support by sharing this article with your friend:

Leave a Reply

Your email address will not be published. Required fields are marked *