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

Angular 5文本框仅允许输入负数的实现方法咨询

Angular 5实现文本框仅允许输入负数的方案

方案一:Reactive Form自定义验证器

针对你使用的Reactive Form,通过添加自定义验证规则,可在输入及提交阶段校验内容是否为负数。

  1. 在组件类中定义验证器函数并绑定到表单控件:
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from '@angular/forms';

// 自定义负数验证逻辑
function negativeNumberValidator(control: AbstractControl): ValidationErrors | null {
  const value = control.value;
  // 空值由required校验,此处仅验证非空值是否为负数
  if (value !== null && value !== '' && (!Number.isFinite(value) || value >= 0)) {
    return { notNegative: true };
  }
  return null;
}

export class YourComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      lowerBoundNumber: ['', [Validators.required, negativeNumberValidator]]
    });
  }
}
  1. 更新模板中的错误提示:
<mat-form-field class="col--sm-4 col--md-4 col--lg-6">
  <input type="number" matInput placeholder="Lower Band Rng" formControlName="lowerBoundNumber" required>
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('required')">Please enter Lower Band Rng</mat-error>
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('notNegative')">Only negative numbers are allowed</mat-error>
  <mat-hint>Enter Lower Band Rng here</mat-hint>
</mat-form-field>

方案二:自定义指令实时拦截输入

通过自定义指令监听输入事件,直接过滤非负数内容,用户输入时会自动清除不符合规则的字符,体验更直观。

  1. 创建自定义指令:
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appNegativeNumberOnly]'
})
export class NegativeNumberOnlyDirective {
  constructor(private ngControl: NgControl) {}

  @HostListener('input', ['$event']) onInputChange(event: any) {
    const inputValue = event.target.value;
    // 仅保留负号开头的数字,允许空值
    const filteredValue = inputValue.replace(/^(?!-)[0-9]*/g, '').replace(/^-([^0-9].*)?$/, '-');
    // 同步更新表单控件值,避免数据不一致
    this.ngControl.control.setValue(filteredValue);
  }
}
  1. 在模块中声明并导出指令:
import { NgModule } from '@angular/core';
import { NegativeNumberOnlyDirective } from './negative-number-only.directive';

@NgModule({
  declarations: [NegativeNumberOnlyDirective],
  exports: [NegativeNumberOnlyDirective]
})
export class YourDirectiveModule {}
  1. 在模板中使用指令:
<mat-form-field class="col--sm-4 col--md-4 col--lg-6">
  <input type="number" matInput placeholder="Lower Band Rng" formControlName="lowerBoundNumber" 
         required appNegativeNumberOnly>
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('required')">Please enter Lower Band Rng</mat-error>
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('notNegative')">Only negative numbers are allowed</mat-error>
  <mat-hint>Enter Lower Band Rng here</mat-hint>
</mat-form-field>

方案三:结合HTML min属性与验证(基础版)

利用number输入框的min属性限制最小值,配合内置验证规则,适合对实时性要求不高的场景:

<mat-form-field class="col--sm-4 col--md-4 col--lg-6">
  <input type="number" matInput placeholder="Lower Band Rng" formControlName="lowerBoundNumber" 
         required min="-999999">
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('required')">Please enter Lower Band Rng</mat-error>
  <mat-error *ngIf="form.get('lowerBoundNumber').hasError('min')">Only negative numbers are allowed</mat-error>
  <mat-hint>Enter Lower Band Rng here</mat-hint>
</mat-form-field>

注意:该方法仅在表单提交或输入框失焦时触发校验,输入过程中仍可输入正数。


内容的提问来源于stack exchange,提问作者Venkatesh R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:15:34