Skip to content

Craft CMS - Making user name fields required

When dealing with fields on the User element in Craft, you can make the custom fields required just like you would any other custom field on an entry element. But a user also comes with a firstName and lastName field, which you can't make required.

When building a site that relied on theses name fields a coupld of weeks ago, I decided to have try and solve this. Here's what I came up with.

When listening for the Element::EVENT_BEFORE_SAVE event on the User::class class, we can check if we have a first & last name before saving, and mark the element as invalid .

Then we add an error to the appropriate field using ->addError(). That will make validation fail, returning the user to the add/edit user screen, with the add alert under each field.

You can add this piece of code to the init() function of a module to make it work.