[英]How to restrict input textbox to enter numbers only in Angular2 form?
I have to restrict user to enter only numbers in a field in Angular2->form I have solution but backspace is not working in input field Can anybody have proper solution for that?我必须限制用户只能在 Angular2->form 的字段中输入数字我有解决方案,但退格在输入字段中不起作用任何人都可以有适当的解决方案吗?
form.html表单.html
<input (keypress)="keyPress($event)" minlength="8" maxlength="15" required />
form.component.ts form.component.ts
keyPress(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
// console.log(inputChar, e.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
On kepress event it restrict user to enter only numbers but problem with this code is backspace, tab keys are not working.So, this code is not as per my expectation...在 kepress 事件中,它限制用户只能输入数字,但此代码的问题是退格键,Tab 键不起作用。所以,此代码不符合我的预期...
I made a directive to prevent specific input, similar to others posted here and in other posts.我做了一个指令来防止特定的输入,类似于在这里和其他帖子中发布的其他人。 I based mine in this article , but made a few changes to avoid using the deprecated
keyCode
attribute, among other things.我在本文中基于我的,但做了一些更改以避免使用已弃用的
keyCode
属性等。
I also lifted the restriction on the allowed keyboard commands (any combination of keys containing Ctrl
, Command
, Shift
or Alt
) because it may lead to unintended restrictions (like being unable to execute the undo/redo command).我还取消了对允许的键盘命令(包含
Ctrl
、 Command
、 Shift
或Alt
任意组合键)的限制,因为它可能会导致意外限制(例如无法执行撤消/重做命令)。
Here is the directive:这是指令:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[inputDigitsOnly]',
})
export class InputDigitsOnlyDirective {
private static readonly allowedKeyCodes = [
"Backspace",
"Delete",
"Insert",
"ArrowUp",
"ArrowRight",
"ArrowDown",
"ArrowLeft",
"Tab",
"Home",
"End",
"Enter",
"Digit1",
"Digit2",
"Digit3",
"Digit4",
"Digit5",
"Digit6",
"Digit7",
"Digit8",
"Digit9",
"Digit0",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
];
@HostListener('keydown', ['$event'])
onKeyDown(e: KeyboardEvent) {
// This condition checks whether a keyboard control key was pressed.
// I've left this 'open' on purpose, because I don't want to restrict which commands
// can be executed in the browser. For example, It wouldn't make sense for me to prevent
// a find command (Ctrl + F or Command + F) just for having the focus on the input with
// this directive.
const isCommandExecution = e.ctrlKey || e.metaKey || e.shiftKey || e.altKey;
const isKeyAllowed = InputDigitsOnlyDirective.allowedKeyCodes.indexOf(e.code) !== -1;
if (!isCommandExecution && !isKeyAllowed) {
e.preventDefault();
return; // let it happen, don't do anything
}
}
}
Then you just need to add the directive in the input:然后你只需要在输入中添加指令:
<input type="text" inputDigitsOnly>
You can change it to fit your needs.您可以更改它以满足您的需要。 You can check the list of available key codes here .
您可以在此处查看可用密钥代码列表。
Hope it helps.希望能帮助到你。
You can achieve that using regex the following way:您可以通过以下方式使用正则表达式来实现:
var numbersOnly = document.getElementById("numbersOnly"); numbersOnly.onkeyup = function myFunction() { numbersOnly.value = numbersOnly.value.replace(/[^0-9]/g, ''); };
<input id="numbersOnly" minlength="8" maxlength="15" required>
How about using the html5 tag?如何使用 html5 标签?
<input type="number">
It 's supported from all browsers.所有浏览器都支持它。
https://www.w3schools.com/html/html_form_input_types.asp https://www.w3schools.com/html/html_form_input_types.asp
you can use this way too你也可以用这种方式
keyPress(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar) && event.charCode != '0') {
event.preventDefault();
}
}
I created a directive that will only allow you to type numbers only.我创建了一个指令,只允许你输入数字。
import { Directive, ElementRef, HostListener, Input,OnInit,Renderer } from '@angular/core';
@Directive({
selector: 'input[app-numeric-field]'
})
export class NumericValidatorDirective implements OnInit {
@Input('app-numeric-field') maxLength: string;
constructor(private elementRef: ElementRef,private _renderer: Renderer) {}
ngOnInit(): void {
this._renderer.setElementAttribute(this.elementRef.nativeElement, 'maxlength', this.maxLength);
}
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if ([46, 8, 9, 27, 13, 110].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();
}
}
}
Then you can use it like this.然后你可以像这样使用它。
<input matInput app-numeric-field>
Backspace will not work because: event.charCode
will not map to one of the digits 0-9
for the backspace key. Backspace 将不起作用,因为:
event.charCode
不会映射到退格键的数字0-9
之一。
You need to whitelist the backspace (ie keyCode = 8).您需要将退格键列入白名单(即 keyCode = 8)。 Something like this (off the top of my head):
像这样的东西(在我的头顶上):
if(event.keyCode != 8 && !pattern.test(inputChar)) {
event.preventDefault();
}
my answer is :- form.html:我的答案是:- form.html:
form.component.ts form.component.ts
restrictNumeric = function (e) {
var input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
if (e.which === 0) {
return true;
}
if (e.which < 33) {
return true;
}
input = String.fromCharCode(e.which);
return !!/[\d\s]/.test(input);
}
Please do not use String.fromCharCode(event.keyCode) any longer, it is marked deprecated MDN and it seems to not working right in Firefox 58. A simple function, tested on Chrome & Firefox:请不要再使用 String.fromCharCode(event.keyCode),它被标记为已弃用的MDN ,它似乎在 Firefox 58 中无法正常工作。一个简单的功能,在 Chrome 和 Firefox 上测试过:
onKeypress(event: any) {
const keyChar = event.key;
let allowCharacter: boolean;
if (keyChar === "-" && event.target.selectionStart !== 0) {
allowCharacter = false;
}
else if (
keyChar === "Tab" ||
keyChar === "Enter" ||
keyChar === "Backspace" ||
keyChar === "ArrowLeft" ||
keyChar === "ArrowRight" ||
keyChar === "Delete") {
allowCharacter = true;
}
else {
allowCharacter = (keyChar >= '0' && keyChar <= '9');
}
if (!allowCharacter) {
event.preventDefault();
}
}
I'm also not happy with this code and hope there exists a better library for this in Angular.我也对这段代码不满意,希望在 Angular 中有一个更好的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.