Regular expression to validate username

后端 未结 10 960
温柔的废话
温柔的废话 2020-11-28 19:27

I\'m trying to create a regular expression to validate usernames against these criteria:

  1. Only contains alphanumeric characters, underscore an
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 19:48

    This one should do the trick:

    if (Regex.IsMatch(text, @"
        # Validate username with 5 constraints.
        ^                          # Anchor to start of string.
        # 1- only contains alphanumeric characters , underscore and dot.
        # 2- underscore and dot can't be at the end or start of username,
        # 3- underscore and dot can't come next to each other.
        # 4- each time just one occurrence of underscore or dot is valid.
        (?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
        # 5- number of characters must be between 8 to 20.
        [A-Za-z0-9_.]{8,20}        # Apply constraint 5.
        $                          # Anchor to end of string.
        ", RegexOptions.IgnorePatternWhitespace))
    {
        // Successful match
    } else {
        // Match attempt failed
    } 
    

提交回复
热议问题