我将以下代码用作TS文件,始终第一个参数在“ ||”之前起作用。只有正则表达式必须被操纵。
phoneNumber: ['', [Validators.required, Validators.pattern(('^[0]{1}[1-9]{9}$')||('^\\+[0-9]{2,3}[0-9]{9}$'))]]
和html看起来像这样
<div>
<label for="phoneNumber">Phone Number</label>
<input formControlName="phoneNumber" placeholder="Phone Number" class="form-control">
<small>e.g. +251912121212, 0912121212</small>
<div *ngIf="phoneNumber.invalid && (phoneNumber.dirty || phoneNumber.touched)">
<small *ngIf="preferenceList.hasError('required',['phoneNumber'])" style="color : red !important;"
class="form-text text-muted">this
field is required
</small>
<small *ngIf="preferenceList.hasError('pattern',['phoneNumber'])" style="color : red !important;"
class="form-text text-muted">Phone
number is not valid yet
</small>
</div>
</div>
如何在同一字段中同时使用两者?
答案 0 :(得分:0)
为了将来参考,我在TS文件中处理了正则表达式,如下所示,效果很好!
phoneNumber: ['', [Validators.required, Validators.pattern('^\\+?[0-9]{3}[0-9]{9}$|[0]{1}[0-9]{9}$')]],