javascript - 将文本输入中的小数限制为最大 100.00 的指令(正则表达式)

标签 javascript regex angular typescript

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

指令代码如下

 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)正则表达式:RegExp = new RegExp(/^(\d{1,2}(\.\d{1,2})?)|(100(\.0 {1,2})?)$/g); 但我仍然可以使用 150%。

我该如何解决这个问题?

最佳答案

它应该匹配所有从 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
    }
  }
}

关于javascript - 将文本输入中的小数限制为最大 100.00 的指令(正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883140/

相关文章:

javascript - 有没有自动缩小和缓存 JavaScript 的插件?

javascript - 是否可以在 Backbone.js 中使用 History.loadUrl 重新加载路由并传入用作成功消息的字符串?

regex - Notepad++ 正则表达式组捕获语法

regex - Perl 基于正斜杠拆分字符串

Angular Reactive Forms - 实现输入组件包装器的最佳方式?

angular - 网页包/Angular 2 : specify order of styles

javascript - 将 Enterprise Architect 图表导出为 XML、JSON 或 Web 友好格式

javascript - Dropzonejs 与 angularjs 的 ng-view

regex - URL 正则表达式不起作用

Angular 2 自定义区域设置