Fetchez la vache
Fetchez la vache

Reputation: 5230

Regex Expression allowing special characters

I'm using an online regex checker such as regex101 to check my regex which is to be used by javascript such as (working but cut down regex for example only)

state = /^[a-zA-Z0-9]$/.test($(control).val())

My Regex is

(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9].{5,19}

Which when cut down into chunks should hopefully mean...

(?=.*[A-Z])  - Must include an Upper case char
(?=.*[0-9])  - Must include a numeric 
[a-zA-Z0-9. ]  - Can include any lower  or upper case char, or Numeric, a period or space
.            - Matching previous
{5,19}       - the string must be 6-20 characters in length

This however still allows special characters such as !.

I've not used \d for decimals as I believe [0-9] should be more strict in this regard, and removed the period and space to see whether this was the cause, to no avail.

Where have I gone wrong to be allowing special characters?

Upvotes: 1

Views: 397

Answers (1)

Mark Walters
Mark Walters

Reputation: 12390

You need to remove the last . which you think is matching previous, it actually matches any character except for newline, so this is where the ! is getting through.

So (?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9].{5,19} should be (?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{5,19}

Also just thought i'd mention there is no difference between \d and [0-9] whatsoever.

UPDATED - this following should fix the issues you were seeing with the regex - (?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9\.\s]{6,20}$

  • Added \. (to allow a .)
  • Added \s (to allow whitespace characters)
  • Changed {5, 19} to {6, 20}$ to ensure the correct character match

If you want to test this version of the regex in regex101 here

Upvotes: 2

Related Questions