1

Here is the Model code with inline validation rule.

namespace app\models;

use Yii;

class Country extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'country';
    }

    public function rules()
    {
        return [
            ...other rules...
            ['pan_no', 'checkPanCardUsers', 'skipOnEmpty' => false, 'skipOnError' => false]
        ];
    }

    public function checkPanCardUsers($attribute, $params)
    {
        ...some condition ...
        $this->addError($attribute, 'custom error message');
    }
}

Controller code

public function actionSomeAction()
{
    $model = new Country();
    if ($model->load(Yii::$app->request->post()) {
        if($model->validate()) {
            $model->save();
        }
    }
    return $this->render('country', [
        'model' => $model,
    ]);
}

But the validation is not working.

7
  • can you show your controller code? because I guess its more a problem of how you have created your model. Commented Sep 29, 2015 at 9:27
  • hmm strange i couldn't see an error from the quick look. I have no clue why you get the error that the addError() function isn't defined. What happens if you log the class inside your model on your custom validation? just to be sure that it is the correct class etc. The problem is normal yii validation rules also using this addError function to add the errors (or at least i am pretty sure they do). So these should also have the same issue. Commented Sep 29, 2015 at 12:00
  • Is your condition returning a correct result? You can use die("Blablabla") to check. Commented Sep 29, 2015 at 12:04
  • if you would remove the condition completly and only use the addError what happens then? Or try to debug with die($this->className()); Commented Sep 29, 2015 at 14:01
  • @BHoft I am not getting any error but the validation is not working. Commented Sep 30, 2015 at 4:20

1 Answer 1

2

Sure just use the following in your rules then your function will be called.

['pan_no', 'checkPanCardUsers', 'skipOnEmpty' => false, 'skipOnError' => false]

and just add your error in your function when your condition is wrong.

public function checkPanCardUsers($attribute, $params)
{
    //...some condition ...
    if (!$this->$attribute !='test')
        $this->addError($attribute, 'custom error message');
}

Hmm strange it works on my test flawlessly..

Check how you have created your model e.g. on create action:

$model = new ModelName();
Sign up to request clarification or add additional context in comments.

2 Comments

updated the question check now. Its not working also
Thanks my code was OK but I was missing id so whole validation was not working.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.