Welcome Guest, Not a member yet? Register   Sign In
Validation rules from both config and controller
#3

[eluser]freeman[/eluser]
Hi, maybe this should help.

Quote:if certain fields have data then I want to validate it, but they’re not required fields

maybe something like

Code:
if($this->input->post('email'))
{
    // not required but checks users table if email already exists
    $this->set_rules('email', 'Mail', 'valid_email|unique[users.email]');
}

Or a combination of rules from config file as well as rules in your controller

Code:
// in your "test" controller

public function add()
{
    $this->load->library('form_validation');
    $this->load->library('my_form_validation');

    $this->form_validation->set_rules('name', 'Name', 'trim|required');

    if($this->input->post('submit'))
    {
        if($this->form_validation->run() == FALSE)
        {
            // gotcha
            $errors = validation_errors();
        }
    }
}

Code:
// my_form_validation.php

private function prep_config_rules($uri = '')
{
    if($uri === '')
    {
        $uri = trim($this->CI->uri->ruri_string(), '/');
    }

    $this->CI->config->load('form_validation', FALSE, TRUE);
    $rules = $this->CI->config->item($uri);

    if(!empty($rules))
    {
        $this->set_rules($rules);
    }
}

public function run($group = '')
{
    $uri = ($group === '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
    $this->prep_config_rules($uri);
    return parent::run($uri);
}

Code:
// app/config/form_validation.php

$config = array(
    'test/add' => array(
        array(
            'field' => 'username',
            'label' => 'Username',
            'rules' => 'required'
        )
    )
);


Messages In This Thread
Validation rules from both config and controller - by El Forum - 10-09-2010, 03:53 AM
Validation rules from both config and controller - by El Forum - 10-12-2010, 01:45 PM
Validation rules from both config and controller - by El Forum - 11-27-2010, 05:54 AM



Theme © iAndrew 2016 - Forum software by © MyBB