Regular Expression to Validate Username

Regular expression to validate username

^(?=.{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})[^_.].*[^_.]$

How to validate a user name with regex?

The specs in the question aren't very clear, so I'll just assume the string can contain only ASCII letters and digits, with hyphens, underscores and spaces as internal separators. The meat of the problem is insuring that the first and last character are not separators, and that there's never more than one separator in a row (that part seems clear, anyway). Here's the simplest way:

/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/

After matching one or more alphanumeric characters, if there's a separator it must be followed by one or more alphanumerics; repeat as needed.

Let's look at regexes from some of the other answers.

/^[[:alnum:]]+(?:[-_ ]?[[:alnum:]]+)*$/

This is effectively the same (assuming your regex flavor supports the POSIX character-class notation), but why make the separator optional? The only reason you'd be in that part of the regex in the first place is if there's a separator or some other, invalid character.

/^[a-zA-Z0-9]+([_\s\-]?[a-zA-Z0-9])*$/

On the other hand, this only works because the separator is optional. After the first separator, it can only match one alphanumeric at a time. To match more, it has to keep repeating the whole group: zero separators followed by one alphanumeric, over and over. If the second [a-zA-Z0-9] were followed by a plus sign, it could find a match by a much more direct route.

/^[a-zA-Z0-9][a-zA-Z0-9_\s\-]*[a-zA-Z0-9](?<![_\s\-]{2,}.*)$/

This uses unbounded lookbehind, which is a very rare feature, but you can use a lookahead to the same effect:

/^(?!.*[_\s-]{2,})[a-zA-Z0-9][a-zA-Z0-9_\s\-]*[a-zA-Z0-9]$/

This performs essentially a separate search for two consecutive separators, and fails the match if it finds one. The main body then only needs to make sure all the characters are alphanumerics or separators, with the first and last being alphanumerics. Since those two are required, the name must be at least two characters long.

/^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$/

This is your own regex, and it requires the string to start and end with two alphanumeric characters, and if there are two separators within the string, there have to be exactly two alphanumerics between them. So ab, ab-cd and ab-cd-ef will match, but a, a-b and a-b-c won't.

Also, as some of the commenters have pointed out, the (_|-| ) in your regex should be [-_ ]. That part's not incorrect, but if you have a choice between an alternation and a character class, you should always go with the character class: they're more efficient as well as more readable.

Again, I'm not worried about whether "alphanumeric" is supposed to include non-ASCII characters, or the exact meaning of "space", just how to enforce a policy of non-contiguous internal separators with a regex.

How to validate username with regular expression

I SOLVED, THANKS.

THE SOLUTION;

^(?!(.*[_].*){2,}$)(?!(.*[0-9].*){4,}$)(?=.{6,20}$)(?![_])[a-zA-Z0-9çÇ_]+(?<![_])$

Regex for validating username

If by "special characters", you mean any non-alphanumeric characters, you may use the following pattern:

^(?=.*[A-Za-z0-9]).{3,30}$

Demo.

Breakdown:

^                   # Beginning of the string.
(?=.*[A-Za-z0-9]) # Must contain at least one alphanumeric (English) character.
.{3,30} # Match any character (special or not) between 3 and 30 times.
$ # End of string.

Further adjustments:

  • If you want to add more characters to the "not special chars", you may add them inside the character class. For example, to add the space char, you may use [A-Za-z0-9 ].

  • If you want to limit the "special characters" to a particular set of characters, then you may replace .{3,30} with [A-Za-z0-9@#$%....]{3,30}.

validate username with regex in javascript

Sometimes writing a regular expression can be almost as challenging as finding a user name. But here you were quite close to make it work. I can point out three reasons why your attempt fails.

First of all, we need to match all of the input string, not just a part of it, because we don't want to ignore things like white spaces and other characters that appear in the input. For that, one will typically use the anchors ^ (match start) and $ (match end) respectively.

Another point is that we need to prevent two special characters to appear next to each other. This is best done with a negative lookahead.

Finally, I can see that the tool you are using to test your regex is adding the flags gmi, which is not what we want. Particularly, the i flag says that the regex should be case insensitive, so it should match capital letters like small ones. Remove that flag.

The final regex looks like this:

/^([a-z0-9]|[-._](?![-._])){4,20}$/

There is nothing really cryptic here, except maybe for the group [-._](?![-._]) which means any of -._ not followed by any of -._.

Regular Expression to validate username with a symbol prefix

The ([a-zA-Z0-9]{0,1})? part in your pattern matches an optional alphanumeric char (1 or 0 occurrences) 1 or 0 times. It means it can match an empty string.

The point here is to match an optional @ first, then use an optional sequence of patterns: an alphanumeric char followed with 0+ alphanumeric chars, . or _:

@?(?:[a-zA-Z0-9][a-zA-Z0-9._]*)?

Since the whole input must be matched, no need using ^ and $ anchors.

Details

  • @? - an optional @
  • (?:[a-zA-Z0-9][a-zA-Z0-9._]*)? - an optional non-capturing group matching a sequence of patterns:

    • [a-zA-Z0-9] - an alphanumeric char
    • [a-zA-Z0-9._]* - 0 or more alphanumeric chars, . or _.

See the regex demo.

Username validation with regular expression in php

The following pattern will work: ^[a-z0-9][a-z0-9_]*[a-z0-9]$

  • ^[a-z0-9]: first character may not be an underscore
  • [a-z0-9_]*: all the others may be anything...
  • [a-z0-9]$: ...except the last one which can't be an underscore.

Regex for username

Let's walk through your rules:

  1. No more than 9 characters
  2. No less than 3 characters

These two can be grouped in the quantifier {3,9} which applies to your entire username. You already use the + quantifier which means "one or more", you can remove that one.

"^[\w\s-]{3,9}$"


  1. No special characters except underscore and hyphen ("_" and "-")

You already covered this, but note that \s means whitespace. You don't mention spaces in your question, are you sure you need those?



  1. Those two characters can't be the one after the other and the username can't start or end with them

Here it gets more tricky. You'll need lookaround assertions to enforce these rules one by one.

First let's start with "Those two characters can't be the one after the other". You can use a negative lookahead before your regex which checks that nowhere two of those are together:

(?!.*[-_]{2,})

The ?! means "the upcoming string shouldn't match the following regex" (aka negative lookahead), and [-_]{2,} means "two or more underscores/dashes".

The next part of the rule is "can't start or end with them". We could create two separate negative lookaheads for this (not starting and not ending with those characters), but as pointed out in the comments you could also combine those into one positive lookahead:

(?=^[^-_].*[^-_]$)

This says the upcoming string must (positive) match "no - or _, then any amount of characters, then again no - or _".


Combine all these lookaheads with the original regex and you get your answer:

"^(?!.*[-_]{2,})(?=^[^-_].*[^-_]$)[\w\s-]{3,9}$"

You can use this tool to test if a regex matches multiple inputs to figure out if it works correctly: http://www.regexplanet.com/advanced/java/index.html



Related Topics



Leave a reply



Submit