Welcome Guest, Not a member yet? Register   Sign In
extended Form Validation/setting custom error messages and errors
#1

[eluser]LAMP Coder[/eluser]
Code:
<?

class My_Form_validation extends CI_Form_validation {

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

    // --------------------------------------------------------------------

    /**
     * Set Rules
     *
     * This function takes an array of field names and validation
     * rules as input, validates the info, and stores it
     *
     * @access    public
     * @param    mixed
     * @param    string
     * @return    void
     */
    function set_rules($field, $label = '', $rules = '', $custom_error = '')
    {
        // No reason to set rules if we have no POST data
        if (count($_POST) == 0)
        {
            return;
        }

        // If an array was passed via the first parameter instead of indidual string
        // values we cycle through it and recursively call this function.
        if (is_array($field))
        {
            foreach ($field as $row)
            {
                // Houston, we have a problem...
                if ( ! isset($row['field']) OR ! isset($row['rules']))
                {
                    continue;
                }

                // If the field label wasn't passed we use the field name
                $label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];

                // Here we go!
                $this->set_rules($row['field'], $label, $row['rules']);
            }
            return;
        }

        // No fields? Nothing to do...
        if ( ! is_string($field) OR  ! is_string($rules) OR $field == '')
        {
            return;
        }

        // If the field label wasn't passed we use the field name
        $label = ($label == '') ? $field : $label;

        // Is the field name an array?  We test for the existence of a bracket "[" in
        // the field name to determine this.  If it is an array, we break it apart
        // into its components so that we can fetch the corresponding POST data later
        if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
        {
            // Note: Due to a bug in current() that affects some versions
            // of PHP we can not pass function call directly into it
            $x = explode('[', $field);
            $indexes[] = current($x);

            for ($i = 0; $i < count($matches['0']); $i++)
            {
                if ($matches['1'][$i] != '')
                {
                    $indexes[] = $matches['1'][$i];
                }
            }

            $is_array = TRUE;
        }
        else
        {
            $indexes     = array();
            $is_array    = FALSE;
        }

        // Build our master array
        $this->_field_data[$field] = array(
                                            'field'                => $field,
                                            'label'                => $label,
                                            'rules'                => $rules,
                                            'is_array'            => $is_array,
                                            'keys'                => $indexes,
                                            'postdata'            => NULL,
                                            'error'                => '',
                                                                                        'custom_error'                  => $custom_error
                                            );
    }


    // --------------------------------------------------------------------

    /**
     * Error String
     *
     * Returns the error messages as a string, wrapped in the error delimiters
     *
     * @access    public
     * @param    string
     * @param    string
     * @return    str
     */
    function error_string($prefix = '', $suffix = '')
    {
        // No errrors, validation passes!
        if (count($this->_error_array) === 0)
        {
            return '';
        }

        if ($prefix == '')
        {
            $prefix = $this->_error_prefix;
        }

        if ($suffix == '')
        {
            $suffix = $this->_error_suffix;
        }

        // Generate the error string
        $str = '';
        foreach ($this->_error_array as $key => $val)
        {
            if ($val != '')
            {
                            if($this->_field_data[$key]['custom_error'] != '')
                                $str .= $prefix.$this->_field_data[$key]['custom_error'].$suffix."\n";
                            else
                $str .= $prefix.$val.$suffix."\n";
            }
        }

        return $str;
    }


     function set_error($error)
    {
        $this->_error_array[] = $error;
    }

    function custom_errors()
    {
        if(sizeof($this->_error_array) > 0)
            return TRUE;
        else
            return FALSE;
    }
    
}
#2

[eluser]LAMP Coder[/eluser]
Modified methods: set_rules, error_string

Why?
I wanted to be able to set custom errors by every field on the run instead of using the field name.

Usage:
Quote: $this->form_validation->set_rules('field_name', 'readable name', 'required', 'This field is require, no matter what!!');


Added methods: set_error, custom_errors

Why?

Sometimes, I had to run some validations based on more then one fields.

I.e. in case if "state" was required in case if user selects "United States" or in something else that i couldn't push through the form validation class.. such as.. if i check the login and login comes out to be incorrect. I should be able to set an error message "Invalid username/password" I know it's not a form validation error... but i wanted i wanted form validation to handle displaying errors,
Quote: $this->form_validation->set_error('Yada Yada Yada!!');

if you're using set_error, you'll have to do following:
Code:
if($this->Form_validation->custom_errors() == FALSE && $this->Form_validation->run() == FALSE)
{
      //no errors, let's do something here
}

instead of:
Code:
if($this->Form_validation->run() == FALSE)
{
      //no errors, let's do something here
}


and last but not the least, you can use following to display the errors
Code:
&lt;?php echo validation_errors(); ?&gt;




Theme © iAndrew 2016 - Forum software by © MyBB