1

I need to validate the form submitted at the frontend by applying additional validation rules.

For that I have created the plugin that listens to "EVENT_BEFORE_SAVE_ENTRY" event and should validate input fields of the form.

Yii2 documentation suggests to override model rules() method to add custom rules, and then to apply validate() method.

The problem is that I cannot find how to override default rules of the Entry class, and how to use overridden classes as entries in Craft3. Also I need to filter saving entry data from script tags of slashes to prevent script injection.

I am quite new to the Craft3, so please prodive some code examples and where exactly should I put my code Thank you in advance!

3

1 Answer 1

2

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' => [],
    ];
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.