Welcome Guest, Not a member yet? Register   Sign In
Custom helper with input validation
#1

[eluser]Fredrik-s[/eluser]
My idea:

- Create a custom helper which could be loaded when checking a input field for min length.
- Creating it as a helper so it could be re-used in different files and keeping it organized and clean.

My controller code below (application/controllers/registration.php):

- Helper "error" below is my own created helper being loaded.
- callback_min_length[2] is my attempt to send the value to the helper function

Code:
// Load helper
$this->load->helper(array('form', 'url', 'error'));
  
// Load library
$this->load->library('form_validation');

    // Set form rules
    $rules = array(
                   array(
                         'field'   => 'firstName',
                         'label'   => 'firstName',
                         'rules'   => 'callback_min_length[2]|trim'
                      )
                );

    $this->form_validation->set_rules($rules);  

    // Set custom error messages

    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('header');
        $this->load->view('view_registration');
        $this->load->view('footer');
    }
    else
    {
        $this->load->view('header');
        $this->load->view('view_registration');
        $this->load->view('footer');
    }

My custom helper code below (application/helpers/error_helper.php):
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    function min_length($str, $val) {

        // Load CI instance to be able to load library
        $ci =& get_instance();

        // Load library
        $ci->load->library('form_validation');

        if (preg_match("/[^0-9]/", $val)) {
            return FALSE;
        }
        if (function_exists('mb_strlen')) {
            if(mb_strlen($str) < $val) {
                $ci->form_validation->set_message('custom_min_length', 'You have to write at least ' . $val . ' characters');
                return FALSE;
            } else {
                return TRUE;
            }
        }
        if(strlen($str) < $val) {
            $ci->form_validation->set_message('custom_min_length', 'You have to write at least ' . $val . ' characters');
            return FALSE;
        } else {
            return TRUE;
        }
    }
?&gt;

I get no output what so ever, not even error message. What am I doing wrong?




Theme © iAndrew 2016 - Forum software by © MyBB