Yii2: how to use custom validation function for activeform?

前端 未结 12 1155
独厮守ぢ
独厮守ぢ 2020-12-25 14:18

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()
    {
          


        
12条回答
  •  孤城傲影
    2020-12-25 14:43

    Your syntax on rules should be something like this man,

    [['birth_date'], 'checkDateFormat']
    

    not this

    ['birth_date', 'checkDateFormat']
    

    So in your case, it should look like below

    ...
    class SignupForm extends Model
    {
        public function rules()
        {
            // Notice the different with your previous code here
            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.'));
        }
    }
    

提交回复
热议问题