【发布时间】:2020-03-26 16:33:43
【问题描述】:
我正在尝试使用角度中的正则表达式验证电话号码
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 位数字后添加空格。
模式无效,电话号码验证错误
Angular 4 Mobile number validation
Regex for field that allows numbers and spaces
屏蔽指令
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);
}
}
【问题讨论】:
-
你在使用响应式表单吗?
-
是的,我正在使用响应式表单
-
正则表达式尝试匹配进行中的令牌 [0-9] 的 12 个字符,但您只输入了 11 个字符,因此会出错
-
是的,我使用的是同一个,但我删除了括号和连字符并尝试进行电话号码验证
标签: javascript angular angular7 angular8 angular-validation