0

I am trying to validate first name and last name on my user registration form. I have tested and the following works for existing users when updating their profile via the form. Both use the onBeforeSaveUser event.

Any ideas why this wouldn't validate for registering users?

public function init()
{
    craft()->on('users.onBeforeSaveUser', function(Event $event)
    {
        craft()->businessLogic_events->onBeforeSaveUser($event);
    });
}

public function onBeforeSaveUser(Event $event)
{
    $user = $event->params['user'];

    if (empty($user->firstName))
    {
        $user->addError('firstName', Craft::t('Name cannot be empty.'));
        $event->performAction = false;
    }

    if (empty($user->lastName))
    {
        $user->addError('lastName', Craft::t('Last Name cannot be empty.'));
        $event->performAction = false;
    }
}
2
  • When testing a new user, does the user account actually get created?
    – Brad Bell
    Aug 24, 2016 at 18:10
  • Ok so I have done some testing. If you hit the submit button and don't fill out any fields. Then the only errors back are Email and Password (standard and set out by Craft). If you do enter an email and password then my validation code works and it errors again this time with the firstName and lastName errors. But these don't trigger on first submit when all fields are blank. Aug 24, 2016 at 20:18

1 Answer 1

2

If you hit the submit button and don't fill out any fields. Then the only errors back are Email and Password (standard and set out by Craft). If you do enter an email and password then my validation code works and it errors again this time with the firstName and lastName errors. But these don't trigger on first submit when all fields are blank.

This is a known issue (specifically with the UserModel when saving a user) because "First Name" and "Last Name" aren't true fields in Craft, but more special case fields.

When saving a user, the UserModel validation runs first and immediately bails when the validation error occurs before the onBeforeSaveUser event fires not giving any plugins a chance to participate.

This will be fixed in the upcoming Craft 3 release.

Your Answer

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

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