Last active
September 11, 2021 03:18
-
-
Save terdelyi/c39701cb75ea9142143f0ac7f99daa5a to your computer and use it in GitHub Desktop.
CraftCMS 3 - Extending the validation on the public user registration form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Craft; | |
use craft\base\Element; | |
use craft\elements\User; | |
use craft\events\ModelEvent; | |
use yii\base\Event; | |
// Place the following lines in the init() function of a module or a plugin. | |
$request = Craft::$app->getRequest(); | |
Event::on( | |
User::class, | |
Element::EVENT_BEFORE_VALIDATE, | |
function (Event $event) use($request) { | |
// If a user already logged in we are not on the public registration page | |
if (Craft::$app->getUser()->getIdentity()) | |
return; | |
// Do the custom validation | |
if (!$event->sender->firstName) { | |
$event->sender->addError('firstName', Craft::t('yii', '{attribute} cannot be blank.', [ 'attribute' => Craft::t('app', 'First Name') ])); | |
$event->isValid = false; | |
} | |
if (!$event->sender->lastName) { | |
$event->sender->addError('lastName', Craft::t('yii', '{attribute} cannot be blank.', [ 'attribute' => Craft::t('app', 'Last Name') ])); | |
$event->isValid = false; | |
} | |
if (!$event->sender->email) { | |
$event->sender->addError('email', Craft::t('yii', '{attribute} cannot be blank.', [ 'attribute' => Craft::t('app', 'Email') ])); | |
$event->isValid = false; | |
} | |
if ($request->post('userConfirm') != 1) { | |
Craft::$app->getSession()->setFlash('userConfirm', 'Ticking that field is required.'); | |
$event->isValid = false; | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. This has been really helpful. The event also gets fired on the reset password page so I added in this check. Perhaps there's a more elegant way to do it?
if ($request->getFullPath() === 'account') { }