Html Angular2-仅接受数字的输入字段
在Angular 2中,如何屏蔽输入字段(文本框),使其只接受数字而不接受字母字符Html Angular2-仅接受数字的输入字段,html,angular,input,angularjs-directive,Html,Angular,Input,Angularjs Directive,在Angular 2中,如何屏蔽输入字段(文本框),使其只接受数字而不接受字母字符 import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[numberOnly]' }) export class NumbersOnlyDirective { private regex: RegExp = new RegExp(/[0-9]/g);
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
我有以下HTML输入:
<input
type="text"
*ngSwitchDefault
class="form-control"
(change)="onInputChange()"
[(ngModel)]="config.Value"
(focus)="handleFocus($event)"
(blur)="handleBlur($event)"
/>
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
上述输入为通用文本输入,可作为简单文本字段或数字字段使用,例如,用于显示年份
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
使用Angular 2,如何使用相同的输入控件并在此字段上应用某种过滤器/掩码,使其仅接受数字
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
我有哪些不同的方法可以实现这一点
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
注意:我需要只使用文本框而不使用输入数字类型来实现这一点。您需要使用type=“number”来代替文本。还可以指定最大和最小数字
<input type="number" name="quantity" min="1" max="5">
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
您可以使用angular2指令
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
import{Directive,ElementRef,HostListener,Input}来自“@angular/core”;
@指示({
选择器:“[OnlyNumber]”
})
仅导出类编号{
构造函数(私有el:ElementRef){}
@Input()OnlyNumber:布尔值;
@HostListener('keydown',['$event'])onKeyDown(event){
设e=事件;
如果(此.OnlyNumber){
if([46,8,9,27,13,110,190]).indexOf(e.keyCode)!=-1||
//允许:Ctrl+A
(e.keyCode===65&(e.ctrlKey | | e.metaKey))||
//允许:Ctrl+C
(e.keyCode===67&(e.ctrlKey | | e.metaKey))||
//允许:Ctrl+V
(e.keyCode===86&(e.ctrlKey | | e.metaKey))||
//允许:Ctrl+X
(e.keyCode===88&(e.ctrlKey | | e.metaKey))||
//允许:起始、结束、左、右
(e.keyCode>=35&&e.keyCode=35&&e.keyCode你可以这样做
<input type="text" pInputText (keypress)="onlyNumberKey($event)" maxlength="3">
onlyNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
//for Decimal you can use this as
onlyDecimalNumberKey(event) {
let charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
onlyNumberKey(事件){
返回(event.charCode==8 | | event.charCode==0)?null:event.charCode>=48&&event.charCode 31
&&(字符编码<48 | |字符编码>57))
返回false;
返回true;
}
希望这能对你有所帮助。来自@omeralper的答案。
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
我改变了一点,不接受周期ascii(键码110190)。
使用let ch=(e.key);与正则表达式相比,当您更改语言(如泰语或日语)时,它将不接受这些语言的字符
export class OnlyNumber {
regexStr = '^[0-9]*$';
constructor(private el: ElementRef) { }
@Input() OnlyNumber: boolean;
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if (this.OnlyNumber) {
// console.log(event, this.OnlyNumber);
if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1) {
return;
}
let ch = (e.key);
let regEx = new RegExp(this.regexStr);
if(regEx.test(ch))
return;
else
e.preventDefault();
}
}
}
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
仅导出类编号{
regexStr='^[0-9]*$';
构造函数(私有el:ElementRef){}
@Input()OnlyNumber:布尔值;
@HostListener('keydown',['$event'])onKeyDown(event){
设e=事件;
如果(此.OnlyNumber){
//console.log(事件,this.OnlyNumber);
if([46,8,9,27,13].indexOf(e.keyCode)!=-1){
返回;
}
设ch=(e.key);
让regEx=newregexp(this.regexStr);
if(正则表达式测试(ch))
返回;
其他的
e、 预防默认值();
}
}
}
希望这个帮助: < P>我想建立在@ OMalalPB给出的答案上,这在我看来为坚实的解决方案提供了很好的基础。
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
我建议的是使用最新web标准的简化和最新版本。请务必注意,event.keycode已从web标准中删除,将来的浏览器更新可能不再支持它。请参阅
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
此外,该方法
String.fromCharCode(e.keyCode);
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
不保证与用户按下的键相关的键码映射到用户键盘上标识的预期字母,因为不同的键盘配置将导致特定的键码具有不同的字符。使用该键码将引入难以识别的错误,并很容易破坏功能我建议使用event.key,请参阅此处的文档
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
此外,我们只希望结果输出是有效的十进制。这意味着数字1、11.2、5000.2341234应该被接受,但值1.1.2不应该被接受
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
请注意,在我的解决方案中,我排除了剪切、复制和粘贴功能,因为它会打开错误窗口,特别是当人们在相关字段中粘贴不需要的文本时。这需要在键控处理程序上执行清理过程;这不属于此线程的范围
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
这是我提出的解决方案
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[myNumberOnly]'
})
export class NumberOnlyDirective {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home' ];
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;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
从'@angular/core'导入{Directive,ElementRef,HostListener};
@指示({
选择器:“[myNumberOnly]”
})
导出类NumberOnlyDirective{
//允许小数。只允许出现一次\
私有regex:RegExp=newregexp(/^[0-9]+(\.[0-9]*){0,1}$/g);
//允许特殊事件的关键代码。反映:
//退格、制表符、结束、起始
private specialKeys:Array=[‘退格’、‘制表符’、‘结束’、‘主页’];
构造函数(专用el:ElementRef){
}
@HostListener('keydown',['$event']))
onKeyDown(事件:KeyboardEvent){
//允许使用退格键、制表符键、结束键和主控键
if(this.specialKeys.indexOf(event.key)!=-1){
返回;
}
//不要使用event.keycode这是不推荐使用的。
//见:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
让当前值:string=this.el.nativeElement.value;
//我们需要它,因为DOM元素上的当前值
//尚未使用此事件的值更新
let next:string=current.concat(event.key);
if(next&&!String(next).match(this.regex)){
event.preventDefault();
}
}
}
您可以创建此验证器并将其导入组件中。
基本上验证表单输入字符串:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
- 检查没有圆点
- 将字符串转换为数字
- check是一个整数
- 支票大于零
要在项目中实施它,请执行以下操作:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
应用程序文件夹中的建议路径:src/app/validators/number.validator.ts
在组件中导入
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
从“../../validators/number.validator”导入{NumberValidator};
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/[0-9]/g);
// Allow key codes for special events. Reflect :
private specialKeys: Array<number> = [46, 8, 9, 27, 13, 110, 190, 35, 36, 37, 39];
// Backspace, tab, end, home
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
e = <KeyboardEvent>event;
if ((
(this.specialKeys.indexOf(event.which) > -1) ||
// to allow backspace, enter, escape, arrows
(e.which == 65 && e.ctrlKey == true) ||
// Allow: Ctrl+C
(e.which == 67 && e.ctrlKey == true) ||
// Allow: Ctrl+X
(e.which == 88 && e.ctrlKey == true))) {
return;
} else if (// to allow numbers
(e.which >= 48 && e.which <= 57) ||
// to allow numpad number
(event.which >= 96 && event.which <= 105)) { }
else {
event.preventDefault();
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if ((next && !String(next).match(this.regex)) ||
(this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
}
将其添加到表单控件
inputNumber:[''[NumberValidator.isInteger]],
如果你不
<input NumbersOnly
[allowDecimals]="true"
[allowSign]="true"
type="text">
<input type="text" (keypress)="numericOnly($event)">
numericOnly(event): boolean {
let patt = /^([0-9])$/;
let result = patt.test(event.key);
return result;
}
import { Directive, ElementRef, Input, HostListener } from '@angular/core';
@Directive({
selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) { }
@Input() maxlength: number;
@Input() min: number;
@Input() max: number;
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
const current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
const next: string = current.concat(event.key);
if (next && !String(next).match(this.regex) || (this.maxlength && next.length > this.maxlength) ||
(this.min && +next < this.min) ||
(this.max && +next >= this.max)) {
event.preventDefault();
}
}
@HostListener('paste', ['$event']) onPaste(event) {
// Don't allow pasted text that contains non-numerics
const pastedText = (event.originalEvent || event).clipboardData.getData('text/plain');
if (pastedText) {
const regEx = new RegExp('^[0-9]*$');
if (!regEx.test(pastedText) || (this.maxlength && pastedText.length > this.maxlength) ||
(this.min && +pastedText < this.min) ||
(this.max && +pastedText >= this.max)) {
event.preventDefault();
}
}
}
}
<input type="text" class="text-area" [(ngModel)]="itemName" maxlength="3" appNumberOnly />
<input type="number" class="form-control" matInput name="value" placeholder="xxx" (change)="xxx()" formControlName="value">
@Directive({
...
selector: '[onlyNumber]'
})
export class OnlyNumberDirective implements ControlValueAccessor {
private onChange: (val: string) => void;
...
private value: string;
constructor(
private elementRef: ElementRef,
private renderer: Renderer2
) {
}
...
@HostListener('input', ['$event.target.value'])
onInputChange(value: string) {
const filteredValue: string = filterValue(value);
this.updateTextInput(filteredValue, this.value !== filteredValue);
}
private updateTextInput(value, propagateChange) {
this.renderer.setProperty(this.elementRef.nativeElement, 'value', value);
if (propagateChange) {
this.onChange(value);
}
this.value = value;
}
// ControlValueAccessor Interface
...
registerOnChange(fn: any): void {
this.onChange = fn;
}
writeValue(value: string): void {
value = value ? String(value) : '';
this.updateTextInput(value, false);
}
}
function filterValue(value): string {
return value.replace(/[^0-9]*/g, '');
}
<input name="number" type="text" onlyNumber [(ngModel)]="someNumber">
import {Directive, ElementRef, HostListener, Output, EventEmitter} from '@angular/core';
//only-digits
@Directive({
selector: '[only-digits]'
})
export class OnlyDigits {
constructor(public el: ElementRef) {
this.el.nativeElement.onkeypress = (evt) => {
if (evt.which < 48 || evt.which > 57) {
evt.preventDefault();
}
};
}
}
<textarea class="form-control" [(ngModel)]="this.myModelVariable"
appOnlyNumbers [allowNegative]="true" [allowMultiLine]="true"
[allowDecimal]="true" [maxLength]="10"
placeholder="Enter values (one per line)"></textarea>
<textarea class="form-control" [(ngModel)]="this.myModelVariable"
appOnlyNumbers [allowMultiLine]="true" [maxLength]="9"
placeholder="Enter values (one per line)"></textarea>
import { Directive, HostListener, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[appOnlyNumbers]'
})
export class OnlyNumbersDirective {
constructor(private el: ElementRef) { }
@Input() allowMultiLine: boolean = false;
@Input() allowNegative: boolean = false;
@Input() allowDecimal: boolean = false;
@Input() maxLength: number = 0;
regex: RegExp;
@HostListener('keypress', ['$event'])
onKeyPress(event: KeyboardEvent) {
this.validate(event, event.key === 'Enter' ? '\n' : event.key);
}
@HostListener('paste', ['$event'])
onPaste(event: Event) {
const pastedText = (<any>window).clipboardData && (<any>window).clipboardData.getData('Text') // If IE, use window
|| <ClipboardEvent>event && (<ClipboardEvent>event).clipboardData.getData('text/plain'); // Non-IE browsers
this.validate(event, pastedText);
}
@HostListener('cut', ['$event'])
onCut(event: Event) {
this.validate(event, '');
}
validate(event: Event, text: string) {
const txtInput = this.el.nativeElement;
const newValue = (txtInput.value.substring(0, txtInput.selectionStart)
+ text + txtInput.value.substring(txtInput.selectionEnd));
if (!this.regex) {
this.regex = <RegExp>eval('/^'
+ (this.allowNegative ? '-?' : '')
+ (this.allowDecimal ? '((\\d+\\.?)|(\\.?))\\d*' : '\\d*')
+ '$/g');
}
var lines = this.allowMultiLine ? newValue.split('\n') : [newValue];
for (let line of lines) {
let lineText = line.replace('\r', '');
if (this.maxLength && lineText.length > this.maxLength || !lineText.match(this.regex)) {
event.preventDefault();
return;
}
}
}
}
@Directive({
selector: '[appOnlyDigits]'
})
export class AppOnlyDigitsDirective {
@HostListener('input', ['$event'])
onKeyDown(ev: KeyboardEvent) {
const input = ev.target as HTMLInputElement;
input.value = String(input.value.replace(/\D+/g, ''));
}
}
<input [(ngModel)]="data" (keypress)="stripText($event)"
class="form-control">
stripText(event) {
const seperator = '^([0-9])';
const maskSeperator = new RegExp(seperator , 'g');
let result =maskSeperator.test(event.key); return result; }
<input type='text' mask="99" formControlName="percentage" placeholder="0">
imports: [
NgxMaskModule.forRoot(),
]