提问人:Rav Kumar 提问时间:10/2/2023 更新时间:10/2/2023 访问量:39
防止用户输入负号,并且仅在 angular 输入字段上输入 0
prevent user from entering negative sign and only 0 on angular input field
问:
我有一个输入字段,当用户输入一个数字时,它将自动转换为负数,该负数正在处理,但我不希望用户手动或阻止他们输入 - (负号)。因此,如果他们从按键中按 - 签名,则不应将其添加到输入字段中。onInputChange
此外,我想防止用户只输入 0,并且只有在另一个数字之后才允许他们输入 0,例如他们可以输入 50、6000、100,000 等,只要它不仅仅是一个 0
#html 代码
<mat-form-field *ngIf="hasCashContribution === 'no'" appearance="fill" class="deal-form-date-picker opacity87" [ngClass]="{'enabled-input': hasCashContribution === 'no'}" style="padding-right: 16px;">
<mat-label [ngClass]="{'alter-text-color': hasCashContribution === 'no'}">Payment</mat-label>
<input matInput
[(ngModel)]="cashContribution"
(ngModelChange)="onInputChange()"
class="alter-text-color"
mask="separator.0"
thousandSeparator=","
[allowNegativeNumbers]="true"
(keypress)="onKeyPress($event)">
<span matPrefix class="alter-text-color" *ngIf="hasCashContribution === 'no'">$</span>
</mat-form-field>
#ts 代码
onInputChange() {
if (this.cashContribution > 0) {
this.cashContribution = -this.cashContribution;
}
}
onKeyPress(event: KeyboardEvent) {
// Check if this.cashContribution is null or undefined
if (this.cashContribution == null) {
return; // Do nothing if cashContribution is null or undefined
}
const inputValue = this.cashContribution.toString();
const keyPressed = event.key;
if (keyPressed === '-' || (keyPressed === '0' && inputValue === '0')) {
event.preventDefault();
}
}
答:
0赞
Bytech
10/2/2023
#1
也许可以使用 min 属性:
<input type="number" min="1">
但是,这里有另一个想法:即使您通过击键防止错误输入,您仍然需要编写逻辑来验证输入。
例如,用户可能会粘贴错误的值,或者使用一些您没有想到的其他方法,这些方法将接受错误的输入,并且可能会破坏您的应用程序......编写一个验证程序,然后显示一条合适的错误消息,说明导致值无效的原因。
评论