Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter: change html class when there is a form validation error?

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?

like image 229
GSto Avatar asked Nov 26 '25 19:11

GSto


2 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') ?>" />
like image 171
swatkins Avatar answered Dec 01 '25 13:12

swatkins


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.

like image 37
birderic Avatar answered Dec 01 '25 13:12

birderic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!