You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular mat-input输入限制:禁止负号后输0及手动修改负号

实现带严格限制的自动负数输入框

需求说明

需要实现一个输入框,满足以下核心要求:

  • 用户输入数字时自动转为负数,禁止手动添加负号
  • 负号后不允许输入0(如不能出现-0或-0123这类格式)
  • 不允许手动删除负号
  • 禁止输入任何非数字字符(如字母、特殊符号等)

修改后的解决方案代码

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"
         class="alter-text-color"
         mask="separator.0"
         thousandSeparator=","
         [allowNegativeNumbers]="false"
         (keydown)="onKeyDown($event)"
         (input)="onInput($event)">
  <span matPrefix class="alter-text-color" *ngIf="hasCashContribution === 'no'">$</span>
</mat-form-field>

TypeScript代码

// 拦截键盘输入,阻止无效操作
onKeyDown(event: KeyboardEvent) {
  const inputElement = event.target as HTMLInputElement;
  const currentValue = inputElement.value;

  // 仅允许数字键和必要的控制键(退格、删除、方向键等)
  const isControlKey = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(event.key);
  const isNumberKey = /^[0-9]$/.test(event.key);

  if (!isControlKey && !isNumberKey) {
    event.preventDefault();
    return;
  }

  // 禁止删除负号:输入框仅存负号,或光标在负号位置时拦截删除/退格
  if ((event.key === 'Backspace' || event.key === 'Delete') && currentValue === '-') {
    event.preventDefault();
    return;
  }
  if (event.key === 'Backspace' && inputElement.selectionStart === 1 && currentValue.startsWith('-')) {
    event.preventDefault();
    return;
  }

  // 禁止在负号后直接输入0
  if (currentValue === '-' && event.key === '0') {
    event.preventDefault();
    return;
  }
}

// 处理输入后的值转换,确保格式合法
onInput(event: Event) {
  const inputElement = event.target as HTMLInputElement;
  let inputValue = inputElement.value.replace(/[^0-9-]/g, ''); // 过滤非法字符

  // 强制值以负号开头,自动补全并去重负号
  if (!inputValue.startsWith('-')) {
    inputValue = '-' + inputValue.replace(/-/g, '');
  } else {
    inputValue = '-' + inputValue.substring(1).replace(/-/g, '');
  }

  // 移除负号后的前导0(单个0除外)
  const numericPart = inputValue.substring(1);
  if (numericPart.startsWith('0') && numericPart.length > 1) {
    inputValue = '-' + numericPart.replace(/^0+/, '');
  }

  // 处理空值或无效格式
  if (inputValue === '-' || inputValue === '-0') {
    inputElement.value = '';
    this.cashContribution = null;
    return;
  }

  // 绑定合法负数到ngModel
  const numericValue = parseFloat(inputValue.replace(/,/g, ''));
  if (!isNaN(numericValue)) {
    this.cashContribution = numericValue;
  } else {
    inputElement.value = '';
    this.cashContribution = null;
  }
}

关键逻辑说明

  1. 键盘事件拦截:

    • 直接过滤非数字、非控制键的输入,从源头阻止非法字符
    • 精准拦截删除负号的操作,确保负号始终存在(除非输入框为空)
    • 实时阻止在负号后输入0的行为
  2. 输入后格式校正:

    • 自动补全负号,用户无需手动输入
    • 清理负号后的前导0,保证数值格式合法
    • 处理空值和无效情况,避免绑定错误数值

内容的提问来源于stack exchange,提问作者Rav Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:18:11