I ended up using the Ad Hoc Validation method of Yii2, here is the link for documentation:
https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation
My code for validation:
Plugin.php
class Plugin extends \craft\base\Plugin
{
public function init()
{
parent::init();
$this->setComponents([
'form1Validator' => Form1Validator::class,
...
]);
Event::on(
SaveController::class,
SaveController::EVENT_BEFORE_SAVE_ENTRY,
function(SaveEvent $event) {
try {
$response = null;
switch($event->entry->section->handle) {
case 'form1':
$response = Plugin::getInstance()->form1Validator->validate($event->entry);
break;
...
}
}
if(!isset($response) || !$response['success']){
$event->isValid = false;
$event->entry->addErrors($response['errors']);
}
} catch (\Exception $e) {
$event->isValid = false;
$event->entry->addError('exception', $e->getMessage());
return;
}
}
);
}
}
Form1Validator.php
class Form1Validator
{
public function validate(Entry $entry)
{
$model = new DynamicModel(
[
'formGender' => $entry->formGender,
'formFirstName' => $entry->formFirstName,
'formLastName' => $entry->formLastName,
'formEmailAddress' => $entry->formEmailAddress,
'formPhoneNumber' => $entry->formPhoneNumber,
]
);
if(!$model
->addRule(['formGender', 'formFirstName', 'formLastName', 'formEmailAddress'], 'required')
->addRule('formGender', 'in', ['range' => ['male', 'female']])
->addRule('formEmailAddress', 'email')
->addRule('formPhoneNumber', 'match', ['pattern' => '/^[0-9]+$/'])
->validate()
) {
return [
'success' => false,
'errors' => $model->getErrors(),
];
}
return [
'success' => true,
'errors' => [],
];
}
}