Yii2: how to use custom validation function for activeform?

Hi guys

I have a form Message

In which there are 2 fields


message

and


file

I want the validator to validate either one of them field as required

Here is what i have done until now but its not working




public function rules()

    {

        return [

            [['sender_id', 'receiver_id'], 'integer'],

            [['message'], 'string'],

            [['message','file'],'my_required'],

            [['is_delivered', 'is_notified', 'is_deleted', 'is_group'], 'boolean'],

            [['created_date', 'updated_date'], 'safe'],

            [['image'], 'string', 'max' => 500],

            [['file'], 'file', 'extensions'=>'jpg, gif, png, pdf'],

        ];

    }


    public function my_required($attribute_name, $params)

    {

        if (empty($this->file)

            && empty($this->message)

        ) {

            $this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));


            return false;

        }


        return true;

    }






Here is the code of my form




<div class="row">

    <p>

        <?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data','id' => 'message-form']]); ?>


    <div class="form-group col-xs-3 col-lg-3">

        <?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>

    </div>

    <div class="form-group col-xs-3 col-lg-3">

        <?= $form->field($model, 'file')->fileInput() ?>

        <?= $form->field($model, 'keys')->hiddenInput()->label(false); ?>


        <div class="form-group">

            <?= Html::submitButton('Send',['class' => 'btn btn-danger','data-placement'=>'right','id'=>'sendMessage']) ?>

        </div>

    </div>

    <?php ActiveForm::end(); ?>

    </p>

</div>



I also tried to use this but it didnt work as well




public function rules()

{

    return [

        [['sender_id', 'receiver_id'], 'integer'],

        [['message'], 'string'],

        [['is_delivered', 'is_notified', 'is_deleted', 'is_group'], 'boolean'],

        [['created_date', 'updated_date'], 'safe'],

        [['image'], 'string', 'max' => 500],

        [['file'], 'file', 'extensions'=>'jpg, gif, png, pdf'],

        ['file', 'required', 'when' => function($model) {

            return empty($model->message);

        }],

    ];

}



I have also tried using inline validation like this




['file', function ($attribute,$model) {

        if (empty($model->message)) {

            $this->addError($attribute, 'Form must contain a file or message.');

        }

    }],



But that did not work out either…

What is the message you are receiving? Is it working if you populate both fields?

try this:





    public function my_required($attribute_name, $params)

    {

        if (empty($this->file)

            && empty($this->$attribute_name)

        ) {

            $this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));


            return false;

        }


        return true;

    }




i tried that and its not working

is there any way to validate that form via javascript????

and i am not getting any error message but it just doesnt validate

I’m confused with few thigs when you say custom validation is not working. Please answer the following questions:

Are your records saved in a database when you don’t populate both fields?

Do you get any error message when you leave both fields empty?

Please can you use errorSummary function to print your messages?

I cannot see any error messages but regardless of the validation

the data is being stored in the database

Old thread but ranks high in Googles searchresults so I leave my comment anyway.

Don’t forget to call $model->validate() in you controller if you want your custom validation to run.

Does this solve?

In Modelo

public function rules()

{

return [

		…


['email' , 'email_existe'],

];

}

public function email_existe($attribute, $params)

{

$email = ["manuel@mail.com","antonio@mail.com"];

foreach(&#036;email as &#036;val)


{

if($this->email == $val)

{

$this->addError($attribute, "Este email já existe");

return true;

}

else

{

return false;

}

}

}

}

author source “6 - Yii Framework 2 - Validar formulario con AJAX (Manuel J. Dávila) youtube”