How to add a new function to the code validation class

i having a function called website_check

function website_check($url){
if ($url !=""){     
    if (preg_match("#^https?://.+#", $url) and fopen($url,"r")){
        return TRUE;
    }else{
        $this->form_validation->set_message('Website url', 'The %s field is invalid');
        return FALSE;
    }       
}else{
    $this->form_validation->set_message('Website url', 'The %s field is required');
    return FALSE;
}

      

}

and I use this function as a special function for checking the shape of the igniter code

$this->form_validation->set_rules('website', 'Website', 'callback_website_check');

      

I use this function in every controller, so I want to add this function to the code form validation class and use it as the default validation function. is it possible to add my function to the code form validation class, if so how can it be done?

+3


source to share


2 answers


Edit the file "system / libraries / Form_validation.php" and insert this new function into the "CI_Form_validation" class.

function website_check($url){  
   if (preg_match("#^https?://.+#", $url) and fopen($url,"r")){
      return TRUE;
   }else{
      return FALSE;
   }       
}

      

Then edit the file 'language / english / form_validation_lang.php' and add this element:



$lang['website_check'] = "The %s field is invalid";

      

then use it like:

$this->form_validation->set_rules('website', 'Website', 'website_check');

      

0


source


Yes. Create a file in your application / library directory named MY_Form_validation.php. Also enter the class name MY_Form_validation. Make sure it extends CI_Form_validation and calls the parent constructor. Then add your rules as methods:

class MY_Form_validation extends CI_Form_validation {

public function __construct()
{
    parent::__construct();
}

public function website_check($url)
{
    if ($url != "") {     
        if (preg_match("#^https?://.+#", $url) and fopen($url,"r")) {
            return TRUE;
        } else {
            return FALSE;
        }       
    }else{
        return FALSE;
    }
}

}

      

You also need to add the rule to the form_validation_lang.php file (in app / language / en). Just add a rule at the bottom:



$lang['website_check']      = "The %s field is invalid.";

      

If the file does not exist, you can copy it from the system / language folder. You should not edit the files in the system folder as they will be overwritten on upgrade.

+2


source







All Articles