尝试在Angular 7中验证input[type=number]
时遇到一个奇怪的问题,希望有人能提供帮助。
<input class="form-control" type="number" name="entranceFee" min="0" [(ngModel)]="entranceFee" #entranceFee="ngModel" pattern="\\d+" [ngClass]="{ 'is-invalid': entranceFee.touched && entranceFee.invalid }" >
<div *ngIf="entranceFee.invalid && entranceFee.touched" class="invalid-feedback">
<div *ngIf="entranceFee.errors.pattern">Only numbers are permitted</div>
<div *ngIf="entranceFee.errors.min">Value cannot be smaller than '0'</div>
</div>
输入将仅接受numbers >= 0
。但是,每当我输入一个数字值(0-9)时,该表格就会失效。为什么?当我在ngAfterViewChecked()
的控制台中输出ngModel时,一个数字值已写入模型。那么如何验证此表格?验证程序中或我的头脑中是否有错误?
使用反应形式和/或input[type=text]
答案 0 :(得分:3)
尝试一下:
<input
class="form-control"
type="number"
name="entranceFee"
#entranceFee="ngModel"
[(ngModel)]="entranceFee.value"
pattern="^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$"
[ngClass]="{ 'is-invalid': entranceFee.touched && entranceFee.invalid }" >
<div *ngIf="entranceFee.invalid && entranceFee.touched" class="invalid-feedback">
<div *ngIf="entranceFee.errors.pattern">Only numbers are permitted</div>
<div *ngIf="entranceFee.errors.min">Value cannot be smaller than '0'</div>
</div>
这是您推荐的Working Sample StackBlitz。
RegEx礼貌-This Answer