I am trying to use CExistValidator inside a controller and can’t figure out a way to correct the errors.
Code:
$existsValidator = new CExistValidator();
$existsValidator->attributeName = 'email';
$existsValidator->className = 'User';
if (!$existsValidator->validate($email))
$message = $this->messages['user']['nonExistentEmail'];
Error
Invalid argument supplied for foreach()
/home/shoaibi/public_html/yii-1.1.8.r3324/framework/validators/CValidator.php(189)
177 /**
178 * Validates the specified object.
179 * @param CModel $object the data object being validated
180 * @param array $attributes the list of attributes to be validated. Defaults to null,
181 * meaning every attribute listed in {@link attributes} will be validated.
182 */
183 public function validate($object,$attributes=null)
184 {
185 if(is_array($attributes))
186 $attributes=array_intersect($this->attributes,$attributes);
187 else
188 $attributes=$this->attributes;
189 foreach($attributes as $attribute)
190 {
191 if(!$this->skipOnError || !$object->hasErrors($attribute))
192 $this->validateAttribute($object,$attribute);
193 }
194 }
195
196 /**
197 * Returns the JavaScript needed for performing client-side validation.
198 * Do not override this method if the validator does not support client-side validation.
199 * Two predefined JavaScript variables can be used:
200 * <ul>
201 * <li>value: the value to be validated</li>
// where $model is a model User
// and parameters could be: array('on'=>'update') or array()
$validator = CValidator::createValidator('exist', $model, 'email', $parameters);
$validator->validate($model);
if ($model->hasErrors())
{
// errors here...
return false;
}
If you look carefully, you will see that validators do work with Models, its attribute EMAIL, is specified in the creation of the validator class. If you wish to just check the ‘email’ of a form, then you will need to create a CFormModel and pass the field ‘email’ as one of its attributes. Exactly, as I wrote on my code.
Yeah, CEmailValidator does that but… CExistsValidator doesn’t and on email case, I think there is no much reason to use an external object-class to perform a simple validation check on a static variable. I guess is on the programmer at the end
I appreciate all of the feedback but we have significantly deviated from the original question here, which was CExistsValidator. Though at this point it seems that using it without a model won’t be possible.