一直试图解决这个问题几个小时。想我会问这里。
我有一个输入字段,如果有人试图输入数字,我只想显示一条消息。我的研究引导我学习ng-pattern,但我似乎无法弄清楚为什么它不能为我工作。
<input
type="string"
class="form-control"
[(ngModel)]="firstName"
name ="firstName"
#studentFirstName ="ngModel"
autocomplete="new-password"
autocomplete="off"
ng-pattern="/^[a-zA-Z\s]*$/"
required>
<div *ngIf="studentFirstName.invalid && (studentFirstName.dirty || studentFirstName.touched)" class="row">
<div class="col-sm-12 text-danger">
The form is invalid somewhere
</div>
<div *ngIf='studentFirstName.errors.required' class="col-sm-12 text-danger">
First Name is required
</div>
<div *ngIf='studentFirstName.errors.pattern' class="col-sm-12 text-danger">
First Name must not contain numbers
</div>
</div>
答案 0 :(得分:1)
使用Angular,您可以使用可用的 PatternValidator
<input
type="string"
class="form-control"
[(ngModel)]="firstName"
name ="firstName"
#studentFirstName ="ngModel"
autocomplete="new-password"
autocomplete="off"
pattern="/^[a-zA-Z\s]*$/" <-----------------pattern
required>
<div *ngIf="studentFirstName.invalid && (studentFirstName.dirty || studentFirstName.touched)" class="row">
<div class="col-sm-12 text-danger">
The form is invalid somewhere
</div>
<div *ngIf='studentFirstName.errors.required' class="col-sm-12 text-danger">
First Name is required
</div>
<div *ngIf='studentFirstName.errors.pattern' class="col-sm-12 text-danger">
First Name must not contain numbers
</div>
</div>