Welcome Guest, Not a member yet? Register   Sign In
Form Validation Extensions: conditional validation method
#1

[eluser]Unknown[/eluser]
Hi all,

Because Codeigniter's form validation does not have a conditional rule (as of yet?), I decided to write one myself. This validation rule takes a comma-separated list of values without spaces.

This piece of code can go directly in your system/libraries/Form_validation.php file:

Code:
/**
     * Needs
     * Checks a comma-separated list of field names.  If any of those field names are empty,
     * the validation fails.
     * Author: Michael Patterson
     * A special thank you to Jeff Pabian, who created with the idea for this method.
     * Date: September 9, 2009
     *
     * @access    public
     * @param    string $str The value of the field -- sent by the class, but unused in this function
     * @param    string $list The comma separated list of fields
     * @return    bool TRUE on validation success, FALSE on failure
     */
    function needs($str, $list)
    {
        $this->CI =& get_instance();
        $this->CI->load->helper ( 'inflector' );

        $group_label = '' ;

        // Try to find a group label
        if ( strpos ( $list , 'label:' ) )
        {
            $group_label = substr ( $list,  strpos ( $list , ',label:' ) + 7 );

            // Strip the label from the field list
            $list  = substr ( $list , 0 , strlen ( $list ) - ( strlen ( $group_label ) + 7 ) );
        }
        

        $list = explode ( ',' , $list );

        //-----------------------------------------------------------
        // Prevent error messages being displayed multiple times
        foreach ( $list as $field )
        {
            if ( array_key_exists ( $field, $this->_error_array ) )
            {
                // If we've already noted an error for this field "group," return true.
                return TRUE;
            }
        }
        //-----------------------------------------------------------

        // Temporarily override the error message

        // Use the group label if it exists
        $label = ( ! empty ( $group_label ) ) ?
            $group_label : '%s' ;

        $this->_error_messages [ 'needs' ] = 'The empty fields from the ' . $label . ' group must be given a value.';

        // Loop the list of fields, if any are empty, return false
        foreach ( $list as $field )
        {
            if ( ! isset ( $_POST [ $field ] )
                || trim ( $_POST [ $field ] ) == ''
            )
            {
                return FALSE ;
            }
        }

        // Nothing was empty!
        return TRUE;
    }

This works great for validating field groups like phone numbers, when you have, as I do, three different fields for the user to enter a phone number. You can also assign group labels! In your system/application/config/form_validation.php file, the code for validating a phone field would be something like this:
Code:
...
  array(
            'field' => 'phone_type',
            'label' => 'phone type',
            'rules' => 'needs[phone_type,phone_1,phone_2,phone_3,label:phone]|max_length[1]|alpha',
        ),
        array(
            'field' => 'phone_1',
            'label' => 'first portion of the phone',
            'rules' => 'needs[phone_type,phone_1,phone_2,phone_3,label:phone]|exact_length[3]|is_natural',
        ),
        array(
            'field' => 'phone_2',
            'label' => 'second portion of the phone',
            'rules'=> 'needs[phone_type,phone_1,phone_2,phone_3,label:phone]|exact_length[3]|is_natural',
        ),
        array(
            'field' => 'phone_3',
            'label' => 'third portion of the phone',
            'rules' => 'needs[phone_type,phone_1,phone_2,phone_3,label:phone]|exact_length[4]|is_natural',
        ),
...

Now, if one of those fields is empty, the validation will fail. It may fail multiple times, but it will only print one error message. The fields will also validate normally. Please also note that the label:<label> argument is optional, but must come last.

Disclaimer: Every code has bugs! Use this method at your own risk.

Enjoy!
#2

[eluser]leftyboy[/eluser]
I like this idea but I can't make it work

I've added the code to the system/libraries/Form_validation.php

and then I'm calling this in my controller:

$this->form_validation->set_rules('telephone', 'Telephone', 'needs[telephone,fax,label:phone]');
$this->form_validation->set_rules('fax', 'Fax', 'needs[telephone,fax,label:phone]');

When I submit a blank form I don't see errors for these 2 fields.

Am I being dim?
#3

[eluser]Unknown[/eluser]
It works for me as expected.

However I did implement it slightly differently;

wrapping it in a class:
Code:
&lt;?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

{original code}

}

and saving it to /system/application/libraries/MY_Form_validation.php as is recommended by the documentation.

My (working) implementation:
Code:
array(
    'field' => 'commercial_project',
    'label' => 'Commercial Project',
    'rules' => 'needs[project_name,project_company_name]'
),
array(
    'field' => 'project_name',
    'label' => 'Project name',
    'rules' => 'trim|xss_clean'
),
array(
    'field' => 'project_company_name',
    'label' => 'Company Name',
    'rules' => 'trim|xss_clean'
),

If 'commercial_project' is set, it requires that project_name and project_company_name are also set.
#4

[eluser]codeninja[/eluser]
How would we handle the radio buttons validation with this?




Theme © iAndrew 2016 - Forum software by © MyBB