javascript - 用于验证电话号码的 Angular 表单验证
问题描述
我正在尝试使用正则表达式以角度验证电话号码
HTML 内容
<div class="form-group row">
<input type="text" class="form-control" appPhoneMask placeholder="Mobile Number" autocomplete="off"
[ngClass]="{ 'is-invalid': (f.inputCountryCode.errors && mobileNumberform.submitted) }"
formControlName="inputCountryCode">
<div *ngIf="(f.inputCountryCode.invalid ) || (f.inputCountryCode.invalid && (f.inputCountryCode.dirty || f.inputCountryCode.touched))"
class="invalid-feedback">
<div *ngIf="f.inputCountryCode.errors.required">This field is required.</div>
<div *ngIf="f.inputCountryCode.errors.pattern">Invalid phone number.</div>
</div>
</div>
TS代码
this.$form = this.$builder.group({
selectCountryCode: [null, Validators.required],
inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{12}")]]
});
验证模式应该允许带空格的数字号码,因为我使用的是电话号码掩码,它在 3 位数字后添加空格。
该模式不起作用,让电话号码验证错误
屏蔽指令
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 <= 9) {
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);
}
}
解决方案
您可以允许:
- 9999 9999
- +61 2 9999 9999
- (02) 9999 9999
Validators.pattern('[- +()0-9]+')
推荐阅读
- docker - 将 png 图像添加到 Dockerfile
- node.js - Setting Google Cloud Storage access-control-allow-origin header still couldn't work
- flutter - 对“this”表达式的引用无效
- java - 如何针对具有 UNION 类型的模式验证 Json
- javascript - 从节点 repl 执行 jest 测试语句
- javascript - 高频更新 Firestore 文档字段
- java - 从 Mainactivity 获取 textview 数据到片段
- css - 如何在不缓存 CSS 样式的情况下有条件地在 Next.js 中渲染组件?
- javascript - 无法制作无限轮播
- swift - Swift 中未释放内存