user4379225
user4379225

Reputation: 23

Regex to allow alpha numeric but not just numeric with minimum 6 characters and max 100

Minimum characters required 6 and maximum characters 100.

All numeric is not allowed -111111 Alpha numeric is allowed - abc123 Special characters is allowed -_@! Only letters is allowed- abcdefgh

AAAAAA =>OK
111111=> NOT OK
AAA123!=>OK
AAA12 => NOT ok minimum 6 characters 
11111_ =>OK

I tried with this regex ^[a-zA-Z][a-zA-Z0-9]*$..it works but i cannot get the minimum 6 or max 100 in this.

^[a-zA-Z][a-zA-Z0-9]*$

All numeric is not allowed -111111 Alpha numeric is allowed - abc123 Special characters is allowed -_@! Only letters is allowed- abcdefgh

Upvotes: 1

Views: 75

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

Your pattern starts with matching [a-zA-Z]. If it is not required that a-zA-Z should be at the start but only at least 1 times in the whole match, if supported, you could use a positive lookahead to assert the length of 6 - 100.

Then you could make sure to match at least 1 time a-z or A-Z or a special chacter between matching 0+ times [a-zA-Z0-9_@!-]* on the left and on the right:

^(?=.{6,100}$)[a-zA-Z0-9_@!-]*[a-zA-Z_@!-][a-zA-Z0-9_@!-]*$
  • ^ Start of string
  • (?=.{6,100}$) Assert what is on the right is 6 - 100 characters except a newline
  • [a-zA-Z0-9_@!-]* Match 0+ times what is listed in the character class
  • [a-zA-Z_@!-] Match a character a-z or A-Z or a special char without a digit
  • [a-zA-Z0-9_@!-]*Match 0+ times what is listed in the character class
  • $ Assert end of the string

Regex demo

Another option is to a positive and a negative lookahead, 1 to check for the length and the other (?!\d+$) to check if the match does not consists of only digits:

^(?=.{6,100}$)(?!\d+$)[a-zA-Z0-9_@!-]+$

Regex demo

Upvotes: 1

Oflocet
Oflocet

Reputation: 566

You can define a range to help with your length requirements.

^[a-zA-Z][\w\d!_\-@]{5,99}$

The first character being mandatory and the remaining symbols being of length 5 to 99.

As commented by Mr. Artner, you could elaborate on your need so we could provide a better answer.

Upvotes: 0

Related Questions