NatalieMac
NatalieMac

Reputation: 261

Regex for validating statement descriptor for credit card statements

I'm trying to validate a string entered by the user to be used as the statement description on the credit card statement to describe the purchase.

The requirements are:

Here's what I've got so far, which is kind of working:

/^(?=.*?[a-zA-Z])[a-zA-Z0-9]{5,22}$/gm

...in that it correctly checks the length for 5-22 characters long and checks for at least one letter. However, it disallows all special characters and diacritics instead of just the few that aren't allowed. How do I modify it to allow the other allowed characters?

Upvotes: 1

Views: 446

Answers (2)

The fourth bird
The fourth bird

Reputation: 163577

You could use a positive lookahead to assert a character and a negative lookahead to assert not to match any character listed in the character class.

For Javascript you can use the case insensitive flag /i and use [a-z].

Edit: As Wiktor Stribiżew points out, to match only ASCII characters you could use [\x00-\x7F] instead of using a dot.

^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$
  • ^ Start of string
  • (?=.*[a-z]) Positive lookahead to check if there is a ASCII letter
  • (?!.*[<>\\'"]) Negative lookahead to check that there is not any of the chars in the character class
  • [\x00-\x7F]{5,22} Match any ASCII character 5 - 22 times
  • $ End of the string

For example:

const regex = /^(?=.*[a-z])(?!.*[<>\\'"])[\x00-\x7F]{5,22}$/gmi;

See the regex demo

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627371

You may use

/^(?=[^a-z]*[a-z])(?:(?![<>\\'"])[\x00-\x7F]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'"]*[<>\\'"])[\x00-\x7F]{5,22}$/i

If you mean printable ASCII chars are allowed use

/^(?=[^a-z]*[a-z])(?:(?![<>\\'"])[ -~]){5,22}$/i
/^(?=[^a-z]*[a-z])(?![^<>\\'"]*[<>\\'"])[ -~]{5,22}$/i

Details

  • ^ - start of string
  • (?=[^a-z]*[a-z]) - there must be at least 1 ASCII letter in the string
  • (?:(?![<>\\'"])[ -~]){5,22} - five to twenty-two occurrences of any printable ASCII char other than <, >, \, ' and " (if [\x00-\x7F] is used, any ASCII char other than the chars in the negated character class)
  • (?![^<>\\'"]*[<>\\'"]) - no <, >, \, ' and " allowed in the string
  • $ - end of string.

Upvotes: 2

Related Questions