How to make an universal postcode mask for ngx-mask input?

650 views Asked by At

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?

3

There are 3 answers

0
Scryper On

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.

0
Bala Vigness On

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

0
M H On

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.