gpt4 book ai didi

angular - 格式化输入的电话号码成 Angular

转载 作者:行者123 更新时间:2023-12-03 13:44:31 25 4
gpt4 key购买 nike

我已经看到了许多在Angularjs中格式化电话号码输入字段的解决方案,但是我在Angular 7上找不到任何东西。我真正想要的是用户在文本字段中键入以下内容:

123456789



并使文本字段将输入的格式设置为:

(123) 456-789



我该怎么做呢?我发现以下正则表达式可以对其进行验证:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

最佳答案

您可以按照以下方法通过“电话屏蔽指令”进行处理,

export class PhoneMaskDirective {

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 = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
newVal = '';
} else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
} else {
newVal = newVal.substring(0, 10);
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
}
this.ngControl.valueAccessor.writeValue(newVal);
}
}

STACKBLITZ DEMO

关于angular - 格式化输入的电话号码成 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com