如何在 angular material 反应形式上验证手机号码?
How to validate mobile number on angular material reactive form?
app.component.ts
phoneFormControl = new FormControl('', [
Validators.required,
Validators.pattern("[6-9]\d{9}")
])
app.component.html
<mat-form-field>
<input matInput placeholder="Phone Number" [formControl]="phoneFormControl>
<mat-error *ngIf="phoneFormControl.hasError('required')">
Phone Number is <strong>required</strong>
</mat-error>
</mat-form-field>
表单提交错误
pattern:
actualValue: "9120227914"
requiredPattern: "^[6-9]d{9}$"
由于您的模式是 string
,因此应该转义反斜杠。
因此,您需要 Validators.pattern("[6-9]\d{9}")
.
而不是 Validators.pattern("[6-9]\d{9}")
样本:
readonly phoneFormControl = new FormControl('', [
Validators.required, Validators.pattern(("[6-9]\d{9}"))
]);
app.component.ts
phoneFormControl = new FormControl('', [
Validators.required,
Validators.pattern("[6-9]\d{9}")
])
app.component.html
<mat-form-field>
<input matInput placeholder="Phone Number" [formControl]="phoneFormControl>
<mat-error *ngIf="phoneFormControl.hasError('required')">
Phone Number is <strong>required</strong>
</mat-error>
</mat-form-field>
表单提交错误
pattern:
actualValue: "9120227914"
requiredPattern: "^[6-9]d{9}$"
由于您的模式是 string
,因此应该转义反斜杠。
因此,您需要 Validators.pattern("[6-9]\d{9}")
.
Validators.pattern("[6-9]\d{9}")
样本:
readonly phoneFormControl = new FormControl('', [
Validators.required, Validators.pattern(("[6-9]\d{9}"))
]);