when using CodeIgniter's form validation, I see that there is a form_error() function for printing out an error if one exists, and an empty html tag if not. Is there an easy way to do a boolean test if there is an error for a particular field or not? I'd like to change the class of the input element itself instead of just printing out an error. What is the best way to accomplish this?
5 Answers
I'm not somewhere where I can test this, but wouldn't this work?
<?php
if (!empty(form_error('username')))
{
$class = "error";
}
else
{
$class = "valid";
}
?>
<input type="text" name="username" class="<?= $class ?>" value="<?= set_value('username') ?>" />
1 Comment
_error_array of the form validation class, it's a bit annoying - you have to use one of these functions that outputs strings. I had to make my own array by explode("\n", validation_errors()) after setting the error_delmiters to blank (CI hardcodes \n between errors with validation_errors()), and this doesn't even include which field had the error, just the messages. Long way of saying that I think you do have to do something like this, even though it's not exactly elegant.Looking at the source (line 207 of https://github.com/EllisLab/CodeIgniter/blob/v2.1.0/system/libraries/Form_validation.php), form_error() returns an empty string if there is no error associated with the given field. You could check to see what the method returns and use that as the condition for changing the element's class.
Comments
I use it in this way
<div class="control-group <?php if (form_error('group')!="") echo "error"; ?>">
1 Comment
<?= form_error('group') ? 'error' : '' ?>The other option can be style the parent element.
e.g.
i used twitter bootstrap so here is the code
<div class="controls">
<input type="text" name="dob" id="dob">
<?php echo form_error('dob'); ?>
</div>
to style the errors i just added this to the css
> .controls p { color : red; }
The error element is shown in a p tag. Hope it Helps.