user3035145
user3035145

Reputation: 33

yii2 class validator does not exist

Class extends validators.

namespace app\myclass;
use yii\validators\Validator;
class telefoneValidator extends Validator
{
    public function validateAttribute($model, $attribute) {
        parent::validateAttribute($model, $attribute);
        if (!preg_match("^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$", $model->$attribute))  {
            $this->addError($model, $attribute, 'error');

        }
    }           
}

Class app\models\user rules validation/

namespace app\models;

    use Yii;
    use app\myclass\telefoneValidator;

        public function rules()
        {
            return [         
                ['telefone', 'telefoneValidator']
            ];
        }

When you start getting error Exception 'ReflectionException' with message:

Class telefoneValidator does not exist

Upvotes: 2

Views: 4474

Answers (1)

arogachev
arogachev

Reputation: 33548

This declaration is for inline validators that declared as the same class methods (for example when you add public function validateTelefone($attribute, $params) { ... } and 'validateTelephone' as second parameter of validation rule).

For external validators that stored in separate classes you should provide full class name with namespace like so:

use app\myclass\telefoneValidator;

...

['telefone', telefoneValidator::className()],

or

['telefone', 'app\myclass\telefoneValidator'],

Additional notes: I recommend change validator name to TelefoneValidator, since it violates framework classes naming convention.

Upvotes: 4

Related Questions