1

I'm going to check the username via both JavaScript then PHP.

The username can contain English letters, numbers and one hyphen (-).

The username cannot be started with hyphen (-).

The username cannot be finished with hyphen (-).

The username cannot be started with numbers.

The username cannot contain more than one hyphen (-).

The username cannot be shorter than 6 and longer than 20.

abc123 is correct.
abc-123 is correct.
ab12 is wrong: username is shorter than 6 character.
-abc123 is wrong: username is started with hyphen.
abc123- is wrong: username is finished with hyphen.
ab-12-c3 is wrong: username contains more than one hyphen.
123abc is wrong: username is started with numbers.
Milad Rahimi
  • 3,464
  • 3
  • 27
  • 39

2 Answers2

4

You can use

^(?!\d)(?!.*-.*-)(?!.*-$)(?!-)[a-zA-Z0-9-]{6,20}$

See demo

Explanation:

  • ^ - Match at the beginning
  • (?!\d) - Do not match if the string starts with a digit
  • (?!.*-.*-) - Do not match if the string has 2 hyphens in the string
  • (?!.*-$) - Do not match if the string ends with a hyphen
  • (?!-) - Do not match if the string starts with a hyphen
  • [a-zA-Z0-9-]{6,20} - Match 6 to 20 characters from the range specified
  • $ - Assert the end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

You need to use a lookahead based regular expression:

/^(?=.{6,20}$)[a-z][a-z0-9]+(?:-[a-z0-9]+)?$/i

A logical approach using JavaScript, would be:

function _isvalid(str) {
   var re = /^[a-z][a-z0-9]+(?:-[a-z0-9]+)?$/i
   return ((str.length > 5) && (str.length < 21) && re.test(str))
}
hwnd
  • 69,796
  • 4
  • 95
  • 132