1

I need to validate some variables values in Yii;

I dont have a model, and i need a pre build yii public method.

some of them must be integer, other string;

The values are being passed with GET.

I tryed all the validation classes that yii has and none works.

Has anyone tryed this and succeded ?

i need something like:

$validator = new CValidator();

$result = $validator->validate(array($key=>$value));

opened for sugestions

3
  • Why not create a model with validation rules ? It should be easier than using directly CValidator
    – soju
    Sep 25, 2012 at 10:07
  • true, but i need to know if there is another way to do this, cbecause the model will change often and mistakes will be made Sep 25, 2012 at 10:08
  • If your model change you will just have to update validation rules. Otherwise you will have to update your custom validation code, not really proper...
    – soju
    Sep 25, 2012 at 10:12

2 Answers 2

5

You can do it for specific validators:

$Validator = new CEmailValidator;

if($Validator->validateValue($value))
{
    // Valid
}

From the Yii Framework file CEmailValidator.php:

/**
* Validates a static value to see if it is a valid email.
* Note that this method does not respect {@link allowEmpty} property.
* This method is provided so that you can call it directly without going through the model validation rule mechanism.
* @param mixed $value the value to be validated
* @return boolean whether the value is a valid email
* @since 1.1.1
*/
public function validateValue($value)
4

Yii validators are tightly integrated with models. So, atleast you need a dummy model object.

my suggestion would be like... create a dummy form model class..

class MyValidator extends CFormModel {
    public function __get($name) {
        return isset($_POST[$name])?$_POST[$name]:null;
    }

    static function myValidate( Array $rules ) {
        $dummy = new MyValidator();

        foreach($rules as $rule) {
            if( isset($rule[0],$rule[1]) ) {
                $validator = CValidator::createValidator( 
                     $rule[1], 
                     $dummy, 
                     $rule[0], 
                     array_slice($rule,2) 
                );
                $validator->validate($dummy);
            }
            else { /* throw error; */ }
        }

        print_r( $dummy->getErrors() );
        return !$dummy->hasErrors();
    }
}

and use this myValidate static method anywhere just like below...

$rules = array(
    array('name, email', 'required'),
    array('email', 'email'),
);


if( MyValidator::myValidate($rules) ) {
    ....
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.