首页 > 解决方案 > 将文本输入中的十进制数限制为最大 100.00 的指令(正则表达式)

问题描述

我有一个指令,它限制文本输入在文本输入中只写入十进制数字

这是指令的代码

 import { HostListener, Directive, ElementRef } from '@angular/core';

@Directive({
    exportAs: 'decimal-number-directive',
    selector: 'decimal-number-directive, [decimal-number-directive]',
})
export class DecimalNumberDirective {
    private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
    private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home'];
    constructor(private el: ElementRef) {}
    @HostListener('keydown', ['$event'])
    onKeyDown(event: KeyboardEvent): void {
        if (this.specialKeys.indexOf(event.key) !== -1) {
            return;
        }

        const current: string = this.el.nativeElement.value;
        const next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex)) {
            event.preventDefault();
        }
    }
}

这是我使用它的输入

<div class="col-2 pr-0">
                        <label>{{ l('Percent') }}</label>
                        <input
                            class="form-control"
                            type="text"
                            decimal-number-directive
                            name="percent"
                            [(ngModel)]="inquiryItemToAdd.percent"
                            maxlength="64"
                            (ngModelChange)="setTotalPrice()"
                            [readOnly]="!inquiryItemToAdd.servicePriceId || !servicePrice.isPriceCalculated"
                        />
                    </div>

但我可以写例如 155.00 或 155.56。我需要用 100.00 来限制它,因为我用它来写百分比。

我尝试使用这个正则表达式private regex: RegExp = new RegExp(/^(\d{1,2}(\.\d{1,2})?)|(100(\.0{1,2})?)$/g);,但我仍然可以使用 150%。

我该如何解决这个问题?

标签: javascriptregexangulartypescript

解决方案


它应该匹配从 0、0.0、0.00 到 100、100.0、100.00 的所有正数

正则表达式

^(\d{1,2}|\d{1,2}\.\d{1,2}|100\.[0]{1,2}|100)$

https://regex101.com/r/S9fbY7/3


更新

你需要允许。要键入,因为50.不是一个有效的模式,50.8但每次击键都会验证整个正则表达式,所以你需要更新你的代码绕过验证.按下时什么都不做,然后模糊如果值以点结尾可能会删除值或删除点或在点后添加 00

忽略的键:

private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home', '.'];

在 Blur 上,您要验证以 . 结尾的值.。注意根据您的用例选择任何一个选项。

if (val.endsWith('.')) {
  // Option 1 strip the . (dot)
  this.el.nativeElement.value = val.substring(0, val.length - 1); 

  // Option 2 add 00 after the . (dot)
  this.el.nativeElement.value = val + '00'; 

  // Option 3 remove the value all together
  this.el.nativeElement.value = ''; 
}

最终代码

import { HostListener, Directive, ElementRef } from '@angular/core';

@Directive({
  exportAs: 'decimal-number-directive',
  selector: 'decimal-number-directive, [decimal-number-directive]',
})
export class DecimalNumberDirective {
  private regex: RegExp = new RegExp(/^(\d{1,2}|\d{1,2}\.\d{1,2}|100\.[0]{1,2}|100)$/g);
  private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home', '.'];
  constructor(private el: ElementRef) { }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent): void {
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }

  @HostListener('blur', [])
  onBlur(): void {
    const val = this.el.nativeElement.value;
    if (val.endsWith('.')) {
      this.el.nativeElement.value = val.substring(0, val.length - 1); // Option 1 strip the .
      // this.el.nativeElement.value = val + '00'; // Option 2 add 00 after the .
      // this.el.nativeElement.value = ''; // Option 3 remove the value all together
    }
  }
}

推荐阅读