Skip to content

Instantly share code, notes, and snippets.

@terdelyi
Last active September 11, 2021 03:18
Show Gist options
  • Save terdelyi/c39701cb75ea9142143f0ac7f99daa5a to your computer and use it in GitHub Desktop.
Save terdelyi/c39701cb75ea9142143f0ac7f99daa5a to your computer and use it in GitHub Desktop.
CraftCMS 3 - Extending the validation on the public user registration form
<?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;
}
}
);
@shetlandrew
Copy link

shetlandrew commented May 26, 2021

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') { }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment