Register form - max 30 character in username and disable illegal character

Hi, please, how do I set the maximum username length to 30 characters during registration and disable illegal characters

Thank you

package com.mkyong.regex.username;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UsernameValidator {

    // simple regex
    //private static final String USERNAME_PATTERN = "^[a-z0-9\\._-]{5,20}$";

    // strict regex
    private static final String USERNAME_PATTERN =
            "^[a-zA-Z0-9]([._-](?![._-])|[a-zA-Z0-9]){3,18}[a-zA-Z0-9]$";

    private static final Pattern pattern = Pattern.compile(USERNAME_PATTERN);

    public static boolean isValid(final String username) {
        Matcher matcher = pattern.matcher(username);
        return matcher.matches();
    }

}

Something like that, I just don’t know where to put it

Declarative User Profile might be your friend.
It’s still a preview feature, you’ll have to enable it in the config.
Then, this should be possible without any coding.
See docs for details.

1 Like

https://www.keycloak.org/docs/latest/server_admin/#defining-a-user-profile

2 Likes

Thank you very much :slight_smile: