David
David

Reputation: 1245

HTML5 Regex Pattern: Allow alphanumeric and up to 3 spaces, underscores, and hyphens

^[a-zA-Z0-9]*[a-zA-Z0-9 _][a-zA-Z0-9]{2,24}$

That's what I have right now.

I want to require an alphanumeric first; allow for alphanumerics, underscores, hyphens, periods, and spaces; require that it end with an alphanumeric. But I only want to allow as many as 3 of those special characters.

I'm primarily confused about how to limit the number of the special characters.

Upvotes: 1

Views: 4057

Answers (3)

CorrugatedAir
CorrugatedAir

Reputation: 819

^[a-zA-Z0-9]+[ _.-]?[a-zA-Z0-9]*[ _.-]?[a-zA-Z0-9]*[ _.-]?[a-zA-Z0-9]+$

There's probably a better way to do this, but I think you could just have the invalid characters be optional, appearing at most three times, with the other valid characters showing up 0 or more times in between them

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56809

You can also use this regex:

/^(?!(?:[a-z\d]*[_. -]){4})[a-z\d][\w. -]{0,22}[a-z\d]$/i

The look-ahead (?!(?:[a-z\d]*[_. -]){4}) is to check that there are less than 4 appearances of invalid characters. If there are 4 or more, then the pattern inside the negative look-ahead would match, and make the look-ahead fail.

Since the string must start and end with alphanumeric, and the length is at least 2, it is possible to specify [a-z\d] as start and end of the string. The rest of the character in between can contain any of [a-zA-Z0-9_. -] repeated 0 to 22 times, since 2 characters are already use for the starting ending alphanumeric.

Upvotes: 3

Okay, this should be the last edit: Didn't think about the total character limit. Added look-ahead (assuming your flavor of regex supports it).

There may be a better way than this, but it's not coming to me (maybe using lookaheads). Here's what I can think of:

^(?=^.{2,24}$)[a-zA-Z0-9]+([a-zA-Z0-9]*[_\-. ]){0,3}[a-zA-Z0-9]+$

It's not too pretty but it should work.

Upvotes: 1

Related Questions