我创建了一个指令,只接受数字和带指示符号的数字。我的代码是
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。我在这里测试了正则表达式。它运行良好。
试试这个RegEx:(/^\d*.?\d{0,2}$/g(