2

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
1
  • The autoloader probably can't find it. What is the file path and name of your telefoneValidator class?
    – Phil
    Feb 4, 2015 at 4:51

1 Answer 1

4

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.

4
  • Tried to use ['telefone', telefoneValidator::className()] error Class 'app\myclass\telefoneValidator' not found. Feb 4, 2015 at 5:40
  • Make sure it's placed correctly in folder structure.
    – arogachev
    Feb 4, 2015 at 5:49
  • Exception 'ReflectionException' with message 'Class yii\validators\telefoneValidator does not exist' in C:\web\vendor\yiisoft\yii2\di\Container.php:411 Probably somewhere in the project need to specify the classpath? Feb 4, 2015 at 6:53
  • No. Where exactly is the file in folder structure?
    – arogachev
    Feb 4, 2015 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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