1

We have developed a Craft 3 site that has user registration. Once a user account has been confirmed and activated, they are shown in a Contacts directory, which other users can search through.

As the user is responsible for adding their own details, a few users have submitted their names in lowercase:

jamie wade instead of Jamie Wade.

Whilst there is nothing wrong with this, it doesn't look great. Is there anyway we can enforce capitalisation in Craft on the users First Name and Last Name fields?

I am aware of Twig's title filter, and this is a good fallback if there isn't anything else.

2

You could easily add client side (JS) validation before the user registration form is submitted. How to do that depends on your JS architecture, I'd use something like vee-validate with a regex validation.

However it would probably be more user friendly to just automatically do the title casing in a custom module, adding something like the following inside the module's init() function:

Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_BEFORE_SAVE_ELEMENT, function(Event $event) {
    if ($event->element instanceof \craft\elements\User) {
        $event->element->firstName = \craft\helpers\StringHelper::titleize($event->element->firstName);
        $event->element->lastName = \craft\helpers\StringHelper::titleize($event->element->lastName);
    }
});

Just beware if you have international users. Who knows what this will do to their names. See Falsehoods programmers believe about names

  • Thanks Udo, that sounds reasonable. That blog post is also a real eye-opener, thanks for sharing! – Jamie Wade Apr 12 '19 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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