I'm trying to create a regular expression to validate usernames against these criteria:
_username
/ username_
/ .username
/ username.
).user_.name
).user__name
/ user..name
).This is what I've done so far; it sounds it enforces all criteria rules but the 5th rule. I don't know how to add the 5th rule to this:
^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$
You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.
This article shows how to use regex to validate a username in Java. Username consists of alphanumeric characters (a-zA-Z0-9), lowercase, or uppercase. Username allowed of the dot (.), underscore (_), and hyphen (-). The dot (.), underscore (_), or hyphen (-) must not be the first or last character.
^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$ └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘ │ │ │ │ no _ or . at the end │ │ │ │ │ │ │ allowed characters │ │ │ │ │ no __ or _. or ._ or .. inside │ │ │ no _ or . at the beginning │ username is 8-20 characters long
If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:
^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$
As much as I love regular expressions I think there is a limit to what is readable
So I would suggest
new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) && !username.StartsWith(".") && !username.StartsWith("_") && !username.EndsWith(".") && !username.EndsWith("_") && !username.Contains("..") && !username.Contains("__") && !username.Contains("._") && !username.Contains("_.");
It's longer but it won't need the maintainer to open expresso to understand.
Sure you can comment a long regex but then who ever reads it has to rely on trust.......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With