Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create one RegEx to validate a username

Tags:

c#

regex

I wrote this code to validate a username meets the given conditions, does anyone see how I can conbine the 2 RegExs into one? Code is c#

    /// <summary>
    /// Determines whether the username meets conditions.
    /// Username conditions:
    /// Must be 1 to 24 character in length
    /// Must start with letter a-zA-Z
    /// May contain letters, numbers or '.','-' or '_'
    /// Must not end in '.','-','._' or '-_' 
    /// </summary>
    /// <param name="userName">proposed username</param>
    /// <returns>True if the username is valid</returns>
    private static Regex sUserNameAllowedRegEx = new Regex(@"^[a-zA-Z]{1}[a-zA-Z0-9\._\-]{0,23}[^.-]$", RegexOptions.Compiled);
    private static Regex sUserNameIllegalEndingRegEx = new Regex(@"(\.|\-|\._|\-_)$", RegexOptions.Compiled);
    public static bool IsUserNameAllowed(string userName)
    {
        if (string.IsNullOrEmpty(userName)
            || !sUserNameAllowedRegEx.IsMatch(userName)
            || sUserNameIllegalEndingRegEx.IsMatch(userName)
            || ProfanityFilter.IsOffensive(userName))
        {
            return false;
        }
        return true;
    }
like image 446
Nathan Avatar asked Feb 04 '11 20:02

Nathan


People also ask

How do you validate a regex pattern?

RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.

How do you validate a username in Python?

The username one works perfectly and the password one does too to an extent. This is my program: import uservalidation # get a username from the user username = input("Username: ") # validate username result, reason = uservalidation.


2 Answers

If I understand your requirements correctly, the below should be what you want. The \w matches letters, digits, or _.

The negative lookbehind (the (?<![-.]) part) allows _ unless the preceding character was . or -.

@"^(?=[a-zA-Z])[-\w.]{0,23}([a-zA-Z\d]|(?<![-.])_)$"
like image 151
Justin Morgan Avatar answered Oct 18 '22 17:10

Justin Morgan


Try adding a greedy + on the last character class and make the middle class non-greedy:

@"^[a-zA-Z][a-zA-Z0-9\._\-]{0,22}?[a-zA-Z0-9]{0,2}$"

this will disallow anything ending in any combination of ., -, or _. This isn't exactly what you have in your original regex, but I figure it's probably what you're going for.

like image 1
kelloti Avatar answered Oct 18 '22 17:10

kelloti