gpt4 book ai didi

angular - Angular 输入[类型=数字]中的验证错误?

转载 作者:行者123 更新时间:2023-12-02 21:26:17 24 4
gpt4 key购买 nike

我在尝试验证 input[type=number] 时遇到一个奇怪的问题在 Angular 7 中,希望有人能提供帮助。

    <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时数值已写入模型。那么我怎样才能验证这个表格呢?验证器或我的头脑中是否存在错误?

使用响应式(Reactive)表单和/或 input[type=text] 实现此代码时也会发生同样的情况

最佳答案

尝试一下:

<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>
<小时/>

Here's a Working Sample StackBlitz for your ref.

<小时/>

正则表达式礼貌 - This Answer

关于angular - Angular 输入[类型=数字]中的验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com