Yii2: how to use custom validation function for activeform?

Luigi Caradonna picture Luigi Caradonna · Jan 6, 2015 · Viewed 62.7k times · Source

In my form's model, I have a custom validation function for a field defined in this way

class SignupForm extends Model
{
    public function rules()
    {
        return [
            ['birth_date', 'checkDateFormat'],

            // other rules
        ];
    }

    public function checkDateFormat($attribute, $params)
    {
        // no real check at the moment to be sure that the error is triggered
        $this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
    }
}

The error message doesn't appear under the field in the form view when I push the submit button, while other rules like the required email and password appear.

I'm working on the Signup native form, so to be sure that it is not a filed problem, I've set the rule

['username', 'checkDateFormat']

and removed all the other rules related to the username field, but the message doesn't appear either for it.

I've tried passing nothing as parameters to checkDateFormat, I've tried to explicitly pass the field's name to addError()

$this->addError('username', '....');

but nothing appears.

Which is the correct way to set a custom validation function?

Answer

TomaszKane picture TomaszKane · Jan 7, 2015

Did you read documentation?

According to the above validation steps, an attribute will be validated if and only if it is an active attribute declared in scenarios() and is associated with one or multiple active rules declared in rules().

So your code should looks like:

class SignupForm extends Model
{
    public function rules()
    {
        return [
            ['birth_date', 'checkDateFormat'],

            // other rules
        ];
    }

    public function scenarios()
    {
        $scenarios = [
            'some_scenario' => ['birth_date'],
        ];

        return array_merge(parent::scenarios(), $scenarios);
    }

    public function checkDateFormat($attribute, $params)
    {
        // no real check at the moment to be sure that the error is triggered
        $this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
    }
}

And in controller set scenario, example:

$signupForm = new SignupForm(['scenario' => 'some_scenario']);