Ionut Flavius Pogacian
Ionut Flavius Pogacian

Reputation: 4801

Yii CValidator Rules : how to validate outside of a model

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

Upvotes: 1

Views: 5703

Answers (2)

JamesG
JamesG

Reputation: 1698

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)

Upvotes: 5

SuVeRa
SuVeRa

Reputation: 2904

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) ) {
    ....
}

Upvotes: 4

Related Questions