Username Checker Example - Length, Profanity, Characters, and Whitespace

Here is my code for checking if the username is suitable as an example. Feel free to use my code if you need.

Network Player →

public bool IsSuitable(string word)
    {
        
        foreach (string badWord in ProfanityWords.profanityArray)
        {
            if (word.ToLower().Contains(badWord) == true)
            {
                Debug.Log("Profanity Detected - Username Denied");
                return false;
                
            }
        }
        char[] charWord = word.ToCharArray();
        char[] allowedLetters = AllowedLetters.allowedChars;
        foreach (char letter in charWord)
        {
            if (allowedLetters.Contains(letter) == false)
            {
                Debug.Log("Disallowed Letter Detected - Username Denied");
                return false;
            }
            
        }
        if (word.Contains(" ") == true)
        {
            Debug.Log("Whitespace Detected - Username Denied");
            return false;
        }
        else if (word.Length < 3 || word.Length > 10)
        {
            Debug.Log("Incorrect Length Detected - Username Denied");
            return false;
        }
        else { return true; }
    }

    [Command]
    private void CmdSetDisplayName(string newDisplayName)
    {
        
        if (IsSuitable(newDisplayName) == false)
        {
            return;
        }
        SetDispName(newDisplayName);
        RpcNotifyDisplayName(newDisplayName);

    }

ProfanityWords.cs →

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class ProfanityWords
{

    // WARNING: Contains sensitive words


    public static string[] profanityArray = { !!! };

}

(for !!!, use the array from this github page - be warned, there are many sensitive words)

AllowedChars.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class AllowedLetters
{

    // Allowed letters in the game under here.

    public static char[] allowedChars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_' };

}

Please leave any feedback or ideas. Thanks for reading!

6 Likes

I think it’s kind of amazing! I really like idea for allowed characters for player’s write! By the way, I am just in “Scope and Context of Variables” lecture, so I guess there is still time until I go in username lecture, but still think it’s cool! :slight_smile:

Privacy & Terms