如何为 ngx-mask 输入制作通用邮政编码掩码?

问题描述 投票:0回答:2

我使用 ngx-mask 14.2.4。我想为我的邮政编码输入字段允许以下条件:

  • 2 到 12 个符号之间
  • 允许使用字母、数字和“-”。也允许空格,但不能在“-”之后。

我尝试过:

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

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

但是没有成功。它不允许我输入特殊字符(空格和 - )。如何达到目标?

angular masking ngx-mask
2个回答
0
投票

您需要转义特殊字符。

逃脱 =>

\s
\ 

“-” =>

\-

“\”=>

\\

正则表达式乍一看非常棘手,当我需要创建一些时,我通常使用这个备忘单


0
投票

像这样更改 Html 中的输入标签,

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

并像这样更改你的 ts 文件,

 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

© www.soinside.com 2019 - 2024. All rights reserved.