我想用这些数字做输入,但是如果我把输入的类型放到文本中我就不会到达我可以放5个字符的字母数字,如果我把输入的类型放到数字我只能放数字但是它不限于5个数字 谢谢大家
HTML
<input type="text" id="number" name="postalCode" placeholder="Saisissez le code postal" formControlName="postalCode" maxlength="5" class="a-textbox" pattern="/^(([0-8][0-9])|(9[0-5]))[0-9]{3}$/" />
角
postalCode: new FormControl('', [Validators.maxLength(5)]),
答案 0 :(得分:0)
您可以尝试此解决方案
上创建了一个演示html代码
<input type="text" OnlyNumber id="number" name="postalCode" placeholder="Saisissez le code postal" formControlName="postalCode" maxlength="5" class="a-textbox" />
OnlyNumber属性指令
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumberDirective {
constructor(private el: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
let e = <KeyboardEvent>event;
/*
8 - for backspace
9 - for tab
13 - for enter
27 - for escape
46 - for delete
*/
if ([8, 9, 13, 27, 46].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+C
(e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+V
(e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+X
(e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
validateFields(event) {
setTimeout(() => {
let numberRegEx = /^[0-9]+$/;
if(!numberRegEx.test(this.el.nativeElement.value)){
this.el.nativeElement.value = "";
event.preventDefault();
}
}, 100)
}
}
答案 1 :(得分:0)
该指令对我来说效果很好,并且具有将其强制为 5 位并排除数字相关字符(例如句点、“e”等)所需的一切。 我建议将输入也保留为文本类型,请参阅此处的推理。 Digit Only Directive in Angular
Angular DigitOnly 指令和掩码指令 https://github.com/changhuixu/ngx-digit-only