<p>I ended up using the Ad Hoc Validation method of Yii2, here is the link for documentation: 
<a href="https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation" rel="nofollow noreferrer">https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation</a></p>

<p>My code for validation: <br>
<strong>Plugin.php</strong></p>

<pre><code>class Plugin extends \craft\base\Plugin

{
    public function init()
{
    parent::init();

    $this-&gt;setComponents([
        'form1Validator' =&gt; Form1Validator::class,
        ...
    ]);

    Event::on(
        SaveController::class,
        SaveController::EVENT_BEFORE_SAVE_ENTRY,
        function(SaveEvent $event) {
            try {
                $response = null;
                switch($event-&gt;entry-&gt;section-&gt;handle) {
                    case 'form1':
                        $response = Plugin::getInstance()-&gt;form1Validator-&gt;validate($event-&gt;entry);
                        break;
                    ...
                        }
                }
                if(!isset($response) || !$response['success']){
                    $event-&gt;isValid = false;
                    $event-&gt;entry-&gt;addErrors($response['errors']);
                }
            } catch (\Exception $e) {
                $event-&gt;isValid = false;
                $event-&gt;entry-&gt;addError('exception', $e-&gt;getMessage());
                return;
            }
        }
    );
}
</code></pre>

<p>}</p>

<p><strong>Form1Validator.php</strong></p>

<pre><code>class Form1Validator
{
 public function validate(Entry $entry)
{
    $model = new DynamicModel(
        [
            'formGender' =&gt; $entry-&gt;formGender,
            'formFirstName' =&gt; $entry-&gt;formFirstName,
            'formLastName' =&gt; $entry-&gt;formLastName,
            'formEmailAddress' =&gt; $entry-&gt;formEmailAddress,
            'formPhoneNumber' =&gt; $entry-&gt;formPhoneNumber,
        ]
    );

    if(!$model
        -&gt;addRule(['formGender', 'formFirstName', 'formLastName', 'formEmailAddress'], 'required')
        -&gt;addRule('formGender', 'in', ['range' =&gt; ['male', 'female']])
        -&gt;addRule('formEmailAddress', 'email')
        -&gt;addRule('formPhoneNumber', 'match', ['pattern' =&gt; '/^[0-9]+$/'])
        -&gt;validate()
    ) {
        return [
            'success' =&gt; false,
            'errors' =&gt; $model-&gt;getErrors(),
        ];
    }

    return [
        'success' =&gt; true,
        'errors' =&gt; [],
    ];
    }
}
</code></pre>

CC BY-SA 4.0
2019-11-25T10:05:54.613Z
2019-11-25T10:38:29.393Z
2019-11-25T10:38:29.393Z
Alex89
<p>I need to validate the form submitted at the frontend by applying additional validation rules.</p>

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

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

<p>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.</p>

<p>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!</p>

CC BY-SA 4.0
2019-11-20T11:22:41.887Z
I recently created a little password confirmation plugin, maybe this is helping you to get started => https://github.com/ChristopherDosin/craft-password-confirm/blob/master/src/PasswordConfirm.php#L69-L84
Christopher Dosin
CC BY-SA 4.0
2019-11-20T13:17:28.427Z
@ChristopherDosin Thank you for the answer, it gave me some clue where to start my search. I found some Ad Hoc validation on Yii2 Documentation and tried to use it in my code https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation
Alex89
CC BY-SA 4.0
2019-11-23T00:07:32.337Z
Be sure and post what ends up working for you as an official answer, @OleksandrStaniev! It might end up helping someone in the future.
Brad Bell
<plugin-development><form><validation>
Frontend form validation
# Frontend form validation

(Asked by: username_0 on 2019-11-20)

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!

**Tags:** plugin-development, form, validation
> **Comments:**
> **username_1**: I recently created a little password confirmation plugin, maybe this is helping you to get started => https://github.com/ChristopherDosin/craft-password-confirm/blob/master/src/PasswordConfirm.php#L69-L84  
> **username_0**: @ChristopherDosin Thank you for the answer, it gave me some clue where to start my search. I found some Ad Hoc validation on Yii2 Documentation and tried to use it in my code https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation  
> **username_2**: Be sure and post what ends up working for you as an official answer, @OleksandrStaniev! It might end up helping someone in the future.  

---

## 1 answers

### Answer by username_0 on 2019-11-25. Score: 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' => [],
    ];
    }
}


---

