I had a simple Password Confirmation validation function in Craft 2. In porting the function to Craft 3, I'm struggling to figure out how to handle the same thing. In Craft 2, all events were consistently handled by setting $event->performAction = false
but in Craft 3, only a subset of events have a similar isValid
option.
Here is my previous Craft 2 version, triggered on onBeforeSaveUser
...
public function confirmPassword($event)
{
// Only do anything if it is a front end submission
// Only validates against passwordConfirm if field is present
if (craft()->request->isSiteRequest()) {
$password = Craft::$app->request->post('password');
$passwordConfirm = Craft::$app->request->post('passwordConfirm');
if (isset($passwordConfirm) && strcmp($password, $passwordConfirm) !== 0) {
$event->user->addErrors(array('passwordConfirm' => Craft::t('Passwords do not match.')));
$event->performAction = false;
}
}
}
In my attempt to port to Craft 3, right now, I'm listening for EVENT_BEFORE_SAVE_ELEMENT
and then doing...
public function confirmPassword(ElementEvent $event)
{
// Only do anything if it is a front end submission
// Only validates against passwordConfirm if field is present
if (Craft::$app->request->isSiteRequest) {
$password = Craft::$app->request->getBodyParam('password');
$passwordConfirm = Craft::$app->request->getBodyParam('passwordConfirm');
if (isset($passwordConfirm) && strcmp($password, $passwordConfirm) !== 0) {
$event->element->addErrors([
'password' => 'Passwords do not match.'
]);
// WHAT DO I DO HERE TO PREVENT USER ELEMENT FROM SAVING?
}
}
}
When I print out $event->element->errors
, it correctly shows the errors. But the element is still saved. Am I missing a step here? Or is there a better way to handle this simple/custom validation?