Angular 2+ SSN掩码允许数字和星号

问题描述

我正在尝试构建一个输入掩码,该掩码将自动格式化用户输入以符合以下条件:

    用户输入“ 999-99-9999”时,
  • ssn必须使用破折号格式
  • ssn必须允许星号(*)。
  • ssn不允许使用字母或数字,“ *”或“-”以外的任何字符。

我当前正在使用以下指令,但是,我不知道如何允许使用星号:

import { Directive,Output,EventEmitter,HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector:'[formControlName][ssn]',})
export class SsnMaskDirective {

  constructor(public ngControl: NgControl) {}

  @HostListener('ngModelChange',['$event'])
  onModelChange(event) {
    this.onInputChange(event,false);
  }

  @HostListener('keydown.backspace',['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value,true);
  }

  onInputChange(event,backspace) {
    let newVal;
    newVal = event.replace(/\D/g,'');

    if (backspace) {
      newVal = newVal.substring(0,newVal.length);
    }

    if (newVal.length === 0) {
      newVal = '';
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/,'$1');
    } else if (newVal.length <= 5) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,2})/,'$1-$2');
    } else if (newVal.length <= 9) {
      newVal = newVal.replace(/^(\d{0,2})(\d{0,4})/,'$1-$2-$3');
    }

    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...