javascript - 如何省略 0 和负数,但用户可以在角材料中输入例如 10
问题描述
所以我有一个 Angular 8 应用程序,我正在使用 Material Angular 库。我有一个数字字段。但我想省略用户输入负数和数字 0。我找到了解决方案。但是现在用户甚至不能输入例如数字 10 - 在这种情况下是一个有效数字。
我有这个:
<ng-container>
<mat-form-field>
<input
matInput
type="number"
formControlName="maxAllowedToScan"
placeholder="Max allowed scanned"
i18n-placeholder
onkeypress="return event.charCode >= 49"
min="1"
/>
<mat-error *ngIf="qrForm.get('maxAllowedToScan').invalid && qrForm.get('maxAllowedToScan').dirty">
{{ errors.maxAllowedToScan }}
</mat-error>
</mat-form-field>
</ng-container>
这就是我在 ts 文件中的内容:
this.qrForm = this.fb.group({
qrcode: [this.definition.qrcode, Validators.required],
title: [this.definition.title, Validators.required],
description: [this.definition.description, Validators.required],
maxAllowedToScan: [
this.definition.maxAllowedToScan // ,
// this.requiredIfScanFrequencyTypeIsNotNone( scanFrequencyTypeControl, 'maxAllowedToScan' )
],
所以我的问题是:如何改善这一点?
谢谢
但如果我这样做:
<ng-container>
<mat-form-field>
<input
matInput
type="number"
formControlName="maxAllowedToScan"
placeholder="Max allowed scanned"
i18n-placeholder
onkeypress="return event.charCode >= 49"
/>
<mat-error *ngIf="qrForm.get('maxAllowedToScan').invalid && qrForm.get('maxAllowedToScan').dirty">
{{ errors.maxAllowedToScan }}
</mat-error>
</mat-form-field>
</ng-container>
那么用户仍然无法输入例如数字 10。
我试过这样:
<ng-container>
<mat-form-field>
<input
matInput
type="number"
formControlName="maxAllowedToScan"
placeholder="Max allowed scanned"
i18n-placeholder
onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
(change) = 'preventLeadingZero()'
/>
解决方案
您可以编写一个简单的函数来处理(keypress)
事件,它将检查输入的长度和输入的 charCode 并防止输入前导零,例如:
function preventLeadingZero(event) {
const input = event.target.value;
if (input.length === 0 && event.which === 48) {
event.preventDefault();
}
}
推荐阅读
- c++ - 编码 2 28BYJ-48 5V DC(电机),带 LJ12A3-4-Z/AX(传感器)
- r - 根据R中不同数据框的变量定义变量
- powershell - 尝试复制继承的权限时出错
- ios - 为什么我的 json 响应不符合我的结构?
- doxygen - 如何基于 *.dox 生成 Doxygen 报告,仅参考源代码
- python - Pandas:组内出现的前 10 个字符串
- firebase - Firebase Image Resizer url 仅在两次提交相同的图像或创建令牌后才有效
- python - 在同一图形上绘制直方图和折线图
- java - 使用 JsonNode 错误地解析日期字段
- javascript - 如何居中并减少这些链接之间的空间?