【发布时间】:2019-05-13 10:15:02
【问题描述】:
我有一个文本输入指令,它替换文本符号并只允许输入十进制数字。
这是该指令的代码
import { NgControl } from '@angular/forms';
import { HostListener, Directive } from '@angular/core';
@Directive({
exportAs: 'decimal-number-directive',
selector: 'decimal-number-directive, [decimal-number-directive]'
})
export class DecimalNumberDirective {
private el: NgControl;
constructor(ngControl: NgControl) {
this.el = ngControl;
}
// Listen for the input event to also handle copy and paste.
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
// Use NgControl patchValue to prevent the issue on validation
this.el.control.patchValue(value.replace(/[^0-9].[^0-9]/, ''));
}
}
现在我可以写 n 个十进制符号了。我只需要两个。我该怎么做?
【问题讨论】:
-
您可以编辑您的问题并向我们展示所有允许的输入吗?
-
尝试像这样指定一个量词:
/[0-9]+.[0-9]{0,2}/ -
您使用了不匹配数字的否定字符类
[^。试试[0-9]+\.[0-9]{2}
标签: javascript regex angular typescript