• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extending Form Validation

#1
[eluser]Whit Nelson[/eluser]
Hello all,

I have a question about form validation: I have several checkboxes, and I want to make sure that at least one is checked. However, each checkbox seems to run through the form validator independently, and so checking that at least one is checked would seem to require a global variable of some sort, which doesn't feel terribly clean to me.

Is there a clean way to run this check on several form elements at once? Can I set a rule which is independent of the form elements themselves, and an error corresponding to it?

Thanks in advance,

Whit

#2
[eluser]Whit Nelson[/eluser]
Ok,

So I added this extension to the Form Validation class. It is from this blog entry here:

http://www.haloweb.co.uk/blog/2009/03/co...ion-class/

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    function My_Form_validation()
    {
        parent::CI_Form_validation();
    }

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

    /**
     * Set Error
     *
     * @access  public
     * @param   string
     * @return  bool
    */  

    function set_error($error = '')
    {
        if (empty($error))
        {
            return FALSE;
        }
        else
        {
            $CI =& get_instance();

            $CI->form_validation->_error_array['custom_error'] = $error;

            return TRUE;
        }
    }

}

?>

This code allows me to create new errors which show up when I call validation_errors(), but I need to display each error individually. I am currently using form_error('rule') to do that. Can anyone shed any light on this?

Thanks,

Whit

#3
[eluser]bretticus[/eluser]
It's actually pretty easy to create a callback that checks to see if at least one of the boxes has been checked.

It'd probably look something like...
Code:
function _got_check_boxen()
    {
        
        if ( $this->input->post('checkbox1')  === FALSE && ...) {
            $this->form_validation->set_message('_got_check_boxen', 'Must choose at least one');
            return FALSE;
        }        
    }

#4
[eluser]Samuurai[/eluser]
Bretticus, this is a great way of doing it... do you need to have a validation rule for every checkbox and specify this callback function, or is there a way of doing it with less lines of code?


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.