Welcome Guest, Not a member yet? Register   Sign In
Form validation by my own method
#8

(This post was last modified: 04-28-2015, 11:51 AM by CroNiX.)

You can always extend the Form_validation library and add your custom rules which would be accessible anywhere the form_validation library is used.
http://www.codeigniter.com/user_guide/ge...-libraries

/application/libraries/MY_Form_validation.php
PHP Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
MY_Form_validation extends CI_Form_validation {
    
    function 
__construct()
    {
        
parent::__construct();
    }

    
//a new custom rule
    
public function custom_rule($input)
    {
        
//$input is the user input for this form field
        
if ($input == "hello")
        {
            return 
TRUE//passed validation
        
} else {
            
//Failed! Set error message (using name of rule)
            
$this->set_message('custom_rule''The %s field can ONLY be "hello".');
        }
        
//If we made it this far, we failed. Send FALSE back
        
return FALSE;
    }


Then in your controller(s):
PHP Code:
$this->form_validation->set_rules('fieldname''field text''trim|custom_rule'); 

You can also create rules that receive extra parameters, which are passed in between the [] when setting the rule, like "min[5]". Anything in [] will automatically be passed to your rule definition as a 2nd parameter

PHP Code:
function some_rule($input$extra '')
{



if you used:
PHP Code:
$this->form_validation->set_rules('fieldname''field text''trim|some_rule[something here]'); 
Then $extra will = "something here" in your rule. Useful for passing in extra parameters if you need them (like identifying a db table). Please note that this value will always be a string passed to the rule.

If you look at how they are creating the native rules in the /system/libraries/Form_validation.php, it could be helpful when creating your custom rules.
Reply


Messages In This Thread
Form validation by my own method - by Valery - 04-25-2015, 09:07 AM
RE: Form validation by my own method - by Valery - 04-28-2015, 04:20 AM
RE: Form validation by my own method - by Valery - 04-28-2015, 04:12 AM
RE: Form validation by my own method - by CroNiX - 04-28-2015, 11:33 AM
RE: Form validation by my own method - by Valery - 04-29-2015, 07:03 AM



Theme © iAndrew 2016 - Forum software by © MyBB