【问题标题】:angular number-only directive accepting two decimals (0..)仅角度数字指令接受两位小数 (0..)
【发布时间】:2018-11-15 20:51:03
【问题描述】:

我创建了一个指令,用于仅接受数字和带十进制的数字。我的代码是

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

@Directive({
    selector: '[number-only]'
})
export class NumberOnlyDirective {
    // Allow decimal numbers and negative values
    private regex: RegExp = new RegExp(/^-?[0-9]+(\.){0,1}([0-9]*){0,1}$/g);
    // Allow key codes for special events. Reflect :
    // Backspace, tab, end, home
    private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Delete"];

    constructor(private el: ElementRef) {
    }
    @HostListener('keydown', ['$event'])
    onKeyDown(event: KeyboardEvent) {
        // Allow Backspace, tab, end, and home keys
        if (this.specialKeys.indexOf(event.key) !== -1) {
            return;
        }
        let current: string = this.el.nativeElement.value;
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex)) {
            event.preventDefault();
        }
    }

}

我将这个指令用作

<input type="number" min="0" class="form-control" number-only />

问题是这个输入元素接受像 5..35 这样的两个小数。 我已经测试了正则表达式here。它工作正常。

【问题讨论】:

    标签: html angular typescript angular-directive


    【解决方案1】:

    试试这个正则表达式:(/^\d*.?\d{0,2}$/g)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多