0

I use ngx-mask 14.2.4. I want to allow the following conditions for my postcode input field:

  • between 2 and 12 signs
  • allow letters, numbers and '-'. Also allow spaces but not after '-'.

I tried:

<input
  type="text"
  [mask]="mask"
  [patterns]="customPatterns"
  [specialCharacters]="['-']"
  [showMaskTyped]="true"
  [dropSpecialCharacters]="false"/>

and

this.mask = '0{12}';
  this.customPatterns = { '0': { pattern: new RegExp('\[A-Za-z0-9- \]')} };

But it didn't work. It doesn't let me input the special characters (space and -). How to achieve the goal?

Hubert Kubiak
  • 607
  • 1
  • 7
  • 30

3 Answers3

0

You need to escape the special characters.

Escape => \s or \

"-" => \-

"\" => \\

Regular expressions are pretty tricky at first sight, I usually use this cheatsheet when I need to create some.

Scryper
  • 178
  • 1
  • 14
0

Change your input tag in Html like this ,

[specialCharacters]="['-', ' ']" <!-- Added space -->

And change your ts file like this,

 mask = 'A{2,12}'; // Adjust the pattern to allow between 2 and 12 characters
  customPatterns = { A: { pattern: new RegExp('[A-Za-z0-9- ]') } }; // Allow letters, numbers, hyphens, and spaces
Bala Vigness
  • 371
  • 1
  • 3
  • 10
0

Try this

this.mask = '0{12}';
this.customPatterns = { '0': { pattern: new RegExp('\[A-Za-z0-9\-\s\]')} };

Although I suspect you'll need to escape the backslashes because the regex is embedded in a string in javascript. So, try this, too:

 this.customPatterns = { '0': { pattern: new RegExp('\[A-Za-z0-9\\-\\s\]')} };

Note that the space and the hyphen are included "literally" by escaping them (reference here: https://www.regular-expressions.info/refcharacters.html)

Also, you probably mean this:

 this.mask = '0{11}';

because thats 12 digits, when you include the first 0 in the count.

M H
  • 325
  • 3
  • 8