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

Angular表单输入框如何限制仅允许特定长度的数字输入?

解决方案:Angular表单限制输入长度为指定数组内的数字位数

针对你需要限制输入为12、14或20位数字的需求,minlength和maxlength无法满足多指定长度的匹配要求,推荐以下两种实现方式:


方法一:模板驱动表单(使用正则表达式)

直接通过pattern指令匹配指定长度的数字,适合简单场景:

<input 
  type="text" 
  name="digitInput" 
  ngModel 
  pattern="^(\d{12}|\d{14}|\d{20})$" 
  #digitInput="ngModel"
  inputmode="numeric"
>

<!-- 错误提示 -->
<div *ngIf="digitInput.invalid && (digitInput.dirty || digitInput.touched)">
  <div *ngIf="digitInput.errors?.['pattern']">
    请输入12位、14位或20位的数字
  </div>
</div>
  • 用type="text"而非number:避免数字类型输入的长度判断异常,同时配合inputmode="numeric"让移动端弹出数字键盘。
  • 正则表达式^(\d{12}|\d{14}|\d{20})$精确匹配12/14/20位纯数字。

方法二:响应式表单(自定义验证器)

适合需要复用验证规则、动态修改允许长度的场景,步骤如下:

1. 创建自定义验证器函数

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// 接收允许的长度数组,返回验证器
export function allowedLengthsValidator(allowedLengths: number[]): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const inputValue = control.value;
    if (!inputValue) return null; // 空值不触发验证,如需必填可单独加required验证

    const inputLength = inputValue.toString().length;
    // 判断输入长度是否在允许列表中
    return allowedLengths.includes(inputLength) ? null : { invalidLength: true };
  };
}

2. 在组件中使用验证器

import { FormBuilder, FormGroup } from '@angular/forms';
import { allowedLengthsValidator } from './your-validator-path';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  digitForm: FormGroup;
  allowedLengths = [12, 14, 20];

  constructor(private fb: FormBuilder) {
    this.digitForm = this.fb.group({
      digitInput: ['', allowedLengthsValidator(this.allowedLengths)]
    });
  }

  // 可选:限制仅能输入数字
  onKeyDown(event: KeyboardEvent) {
    const allowedKeys = ['0','1','2','3','4','5','6','7','8','9','Backspace','Delete','ArrowLeft','ArrowRight','Tab'];
    if (!allowedKeys.includes(event.key)) {
      event.preventDefault();
    }
  }
}

3. 模板中的表单与错误提示

<form [formGroup]="digitForm">
  <input 
    type="text" 
    formControlName="digitInput"
    inputmode="numeric"
    (keydown)="onKeyDown($event)"
  >

  <div *ngIf="digitForm.get('digitInput')?.invalid && (digitForm.get('digitInput')?.dirty || digitForm.get('digitInput')?.touched)">
    <div *ngIf="digitForm.get('digitInput')?.errors?.['invalidLength']">
      请输入{{ allowedLengths.join('、') }}位的数字
    </div>
  </div>
</form>

内容的提问来源于stack exchange,提问作者Ariff Haikal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:57:50