How to check if form field error exists?


I want to add a CSS class to one of my form fields, if there are any errors related, but I couldn’t figure out how to do it.

<div class="control-group <?php if ($form->error($model,'username') != "") echo "error"; ?>">

I tried the above code but it didn’t work. What is the best way to do this?


Assuming you are using CActiveForm, that should work if there is an error present, are you certain there is?

Yes I’m using CActiveForm.

You can find the interesting part below:

<?php echo ‘"’ . $form->error($model,‘username’) . ‘"’; ?>

<?php echo strlen($form->error($model, ‘username’)); ?>



Weird? Am I missing something here?


I looked at the page source and saw this bit:

<div class="errorMessage" id="LoginForm_username_em_" style="display:none"></div>

Now I know why it "renders" nothing but is of length 81.

But, how can I get only if an error exists or not?

Hey frbry,

I’m sorry I made a mistake the first time, CActiveForm::error($model, ‘attribute’); returns the error wrapped in html.

You need to query the actual model to do what you want to do:

<div class="control-group <?php if ($model->error('username') !== null) echo "error"; ?>">

Hope this helps you.

The right way to check for errors is to call the hasErrors() function.