我创建了一个仅接受数字和带小数的数字的指令。我的代码是
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。很好。
答案 0 :(得分:0)
尝试使用此RegEx:(/ ^ \ d *。?\ d {0,2} $ / g)