Codeigniter build validation class at your own needs

落花浮王杯 提交于 2019-12-23 03:39:10

问题


I am working in codeigniter and Iam looking to make my own custom validation class using "Validation_form" library and my custom rule where I will place my own validation rules and use that from everywhere in my project, but this seems impossible, I tried in couples ways to handle this but nothing.

Codeigniter kindle force me to make my callback methods in my controller but I need them in my library or "method" or wherever else!!!

My question is, can I build an specific library where I'll place my validation rules and other functions I need to handle that?


回答1:


you could create a new library in application/libriries and name the file MY_Form_validation

What you are doing here is extending the form_validation class so that you will not need to mess with the core files.

The MY_ is what is set on your config, be sure to check it if you changed yours.

sample MY_Form_validation.php

class MY_Form_validation Extends CI_Form_validation
{
   //this is mandatory for this class
   //do not forget this or it will not work
   public function __construct($rules = array(){
        parent::__construct($rules);
        $this->CI->lang->load('MY_form_validation');
    }
   public function method1($str){
     return $str == '' ? FALSE : TRUE;
   }
   pulic function method2($str)
   {
       //if you want a validation from database
       //you can load it here
       // or check the `form_validation` file on `system/libraries/form_validation`

  }

  public function check_something_with_post($tr)
  {
      return $this->CI->input->post('some_post') == FALSE ? FALSE : TRUE;
  }
}

Basically, when you call a rule sample method1|method2 the value of your post field will be the parameter of the method. if you want to check other post you can do it by using $this->CI->input->post('name of the post');

when you want to pass a parameter just look at the form validation is_unique or unique code on system/libraries/form_validation you will have an idea.

To create a error message that goes with it go to application/language/english/MY_Form_validation_lang

Sample MY_form_validation_lang.php

$lang['method1'] = "error error error.";
$lang['method2'] = "this is an error message.";

if english does not exist on your application/language just create it.

check more atCreating libraries

NOTE:

On some linux or debian server you may want to change the file name from MY_Form_validation to MY_form_validation note the small f on the word form.



来源:https://stackoverflow.com/questions/21046166/codeigniter-build-validation-class-at-your-own-needs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!