Monday, February 21, 2011

CodeIgniter form verification and class

I'm using the form validation library and have something like this in the view

<p>
        <label for="NAME">Name <span class="required">*</span></label>
        <?php echo form_error('NAME'); ?>
        <br /><input id="NAME" type="text" name="NAME" class="" value="<?php echo set_value('NAME'); ?>"  />
</p>

I'd like to add a class to the input that is dependent on the form error so i could have something like this

<input id="NAME" type="text" name="NAME" class="<?php echo $error;?>" value="<?php echo set_value('NAME'); ?>"

I realize that it would have to be a bit more complicated, but I'd like to this this without creating a custom rule callback for every field.

Thanks ~Daniel

From stackoverflow
  • I just realized, there is a way to do this with error delimiters

    $this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
    

    I this makes it much easier.

    But just out of curiosity, Is there any way of doing this with class in the input?

    Thorpe Obazee : What do you mean by class in the input?
    Daniel : Ideally... I'd like to be able to push another variable in. Right now you can set the message to be displayed in the callback. I would like to set an error class to assign css to. This would allow me to style it differently depending on the error.
  • If you set all your validation fields in your controller using:

    $this->validation->set_fields()
    

    You will have access to any possible error messages, which you could use in the following manner:

    <input id="NAME" name="NAME" value="<?php echo $this->validation->NAME; ?>" <?php echo (!empty($this->validation->NAME_error)) ? 'class="error"' : ''; ?> />
    

    http://codeigniter.com/user%5Fguide/libraries/validation.html

    As pointed out in the comments, the code above references the old validation library. The new 1.7 way to perform this task would be:

    <input id="NAME" name="NAME" value="<?php echo set_value('NAME'); ?>" <?php echo (!empty(form_error('NAME')) ? 'class="error"' : ''; ?> />
    
    Thorpe Obazee : This is really really wrong to teach the old validation class. You should go use the new Form Validation class here: http://codeigniter.com/user_guide/libraries/form_validation.html
    cballou : I added a solution for 1.7 as well.

0 comments:

Post a Comment