3

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 5

4

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') ?>" />
Sign up to request clarification or add additional context in comments.

1 Comment

I was just facing a similar issue as I'm rewriting a custom Form library. There's no way to access the _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.
2

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

1

this works for me

<?php 
if(form_error('field_name') != '')
{
   $class = 'error';
}

Not sure why this works when !empty throws the error: Can't use function return value in write context.

Comments

1

I use it in this way

<div class="control-group <?php if (form_error('group')!="") echo "error"; ?>">

1 Comment

Slightly shorter: <?= form_error('group') ? 'error' : '' ?>
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.