I am trying to create a validation function for usernames. It must be:
- Min six characters / Max 16 characters
- Only letters, numbers and, at the most, one hyphen
- It must start with a letter and no end with a hyphen
I came up with this regular expression:
^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$
Which does everything but the maximum number of characters. What am I missing?
You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).
This is a simple validation function in Python:
# Username validation
import re
def validate(username):
regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
match = regex.match(str(username))
return bool(match)
print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
Thanks very much for any suggestion.