Welcome Guest, Not a member yet? Register   Sign In
Form Validation
#2

First: you should always validate form data on the server side. JavaScript validation is nice, but the user has full control over JavaScript, including being able to disable it completely. At the minimum, you should do enough validation on the server to make sure you don't insert something malicious into your database. You should behave as if the JavaScript validation is at best suspect, and at worst compromised or disabled.

I usually submit my form back to the method which originally displayed it, which reduces the need to duplicate code or pass data between methods in my controller just to handle a single form. The view itself just uses set_value() (or the other form_helper set_*() functions, as appropriate) to populate the values, and I usually default the record variable to an empty object if I'm loading an empty form and use isset() to avoid bad property references.

Example from view (excuse the mish-mash of bootstrap v2 classes):
PHP Code:
<?php if (validation_errors()) : ?>
<div class='alert-error'>
    <h4 class='alert-heading'><?php echo lang('example_validation_heading'); ?></h4>
    <?php echo validation_errors(); ?>
</div>
<?php endif; ?>
<?php 
echo form_open($this->uri->uri_string(), 'class="form-horizontal"'); ?>
    <fieldset>
        <div class="control-group<?php echo form_error('field_name') ? ' error' ''?>">
            <label class='form-label' for='field_name'><?php echo lang('field_name'); ?></label>
            <div class='controls'>
                <input id='field_name' name='field_name' type='text' maxlength='255' value="<?php echo set_value('field_name', isset($record->field_name) ? $record->field_name ''); ?>" />
                <span class='help-inline'><?php echo form_error('field_name'); ?></span>
            </div>
        </div>
    </fieldset>
    <fieldset class="form-actions">
        <input type='submit' name='submit' value="<?php echo lang('example_form_submit'); ?>" />
    </fieldset>
<?php 
echo form_close(); 

I probably went overboard with the following controller example. This assumes a few methods are added to the model, so I tried to add comments to vaguely describe what the model might be doing in those cases (to avoid adding an even more detailed example_model to this post).
PHP Code:
<?php 

class Example extends MY_Controller
{
 
   public function __construct()
 
   {
 
       parent::__construct();

 
       // If it's not loaded already by your base controller.
 
       $this->load->library('form_validation');
 
       $this->load->model('example_model');
 
   }

 
   public function create()
 
   {
 
       // If you have some method of access control, this might be a good time
 
       // to make sure the user is authorized to do this.
 
       if (! $this->isAuthorizedUser($this->permissionCreate)) {
 
           redirect();
 
       }

 
       // The vars for use in the view.
 
       $data = array();

 
       // Did the user submit the form? You might want to take this a step further
 
       // and ensure the value is the same as was displayed on the form.
 
       if ($this->input->post('submit')) {
 
           // Validate and save the data input into the form.
 
           if ($insertId $this->saveExample()) {
 
               // indicate success
 
               // ...
 
               redirect('example');
 
           }

 
           // Insert failed, check for errors and send any additional messages
 
           // to the view by adding them to $data. Validation messages should be 
 
           // handled by use of validation_errors() and form_error() in the view.
 
           // ...
 
           $data['error'] = $this->example_model->getErrorMessage();
 
       }

 
       // Populate the vars for use in the view.

 
       // An edit method would call the model to retrieve the record to be edited.
 
       $data['record'] = new stdClass();

 
       $this->load->view('create'$data);
 
   }

 
   protected function saveExample($type 'insert'$id 0)
 
   {
 
       if ($type == 'update') {
 
           // Get the name of the primary key.
 
           $exampleKey $this->example_model->get_key();
 
           // Validate the $id before assigning it here...
 
           $_POST[$exampleKey] = $id;
 
       }

 
       // Get the validation rules from the model.
 
       $this->form_validation->set_rules($this->example_model->get_validation_rules());
 
       if ($this->form_validation->run() === false) {
 
           return false;
 
       }

 
       // Extract only the permitted fields from the post data.
 
       $data $this->example_model->prep_data($this->input->post());

 
       if ($type == 'insert') {
 
           $id $this->example_model->insert($data);
 
           return is_numeric($id);
 
           // To return the inserted ID, it could look something like this:
 
           // return is_numeric($id) ? $id : false;
 
       } elseif ($type == 'update') {
 
           // If prep_data() method doesn't include the key, add it as needed.
 
           // $data[$exampleKey] = $id;
 
           return $this->example_model->update($id$data);
 
       }

 
       return false;
 
   }

Reply


Messages In This Thread
Form Validation - by ignitedcms - 08-04-2015, 11:11 AM
RE: Form Validation - by mwhitney - 08-04-2015, 01:36 PM
RE: Form Validation - by Diederik - 08-04-2015, 03:02 PM
RE: Form Validation - by ignitedcms - 08-04-2015, 03:40 PM
RE: Form Validation - by Diederik - 08-04-2015, 10:36 PM
RE: Form Validation - by ignitedcms - 08-05-2015, 12:08 AM
RE: Form Validation - by mwhitney - 08-05-2015, 07:26 AM
RE: Form Validation - by Diederik - 08-05-2015, 01:43 AM
RE: Form Validation - by Wouter60 - 08-05-2015, 06:50 AM
RE: Form Validation - by CroNiX - 08-05-2015, 07:20 AM
RE: Form Validation - by ignitedcms - 08-05-2015, 11:55 AM
RE: Form Validation - by mariek - 08-14-2015, 08:40 AM
RE: Form Validation - by mwhitney - 08-14-2015, 09:54 AM
RE: Form Validation - by mariek - 08-17-2015, 12:34 AM



Theme © iAndrew 2016 - Forum software by © MyBB