问题描述
我正在尝试构建一个输入掩码,该掩码将自动格式化用户输入以符合以下条件:
-
用户输入“ 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 (将#修改为@)