我必须限制用户只在Angular2->形式的字段中输入数字,我有解决方案,但是backspace不在输入字段中,有人有合适的解决方案吗?
form.html
<input (keypress)="keyPress($event)" minlength="8" maxlength="15" required />
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();
}
}在kepress事件中,它限制用户只输入数字,但是这个代码的问题是后退,选项卡键不是working.So,这段代码不像我预期的那样.
发布于 2016-12-21 21:45:55
我的回答是:- form.html:
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);
}发布于 2020-01-13 15:25:22
我做了一个指令,以防止特定的投入,类似于其他张贴在这里和其他帖子。我的基础是这篇文章,但我做了一些更改,以避免使用废弃的keyCode属性等。
我还取消了对允许的键盘命令(包含Ctrl、Command、Shift或Alt的任何键组合)的限制,因为它可能导致意外的限制(比如无法执行撤销/重做命令)。
以下是指令:
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
}
}
}然后只需在输入中添加指令:
<input type="text" inputDigitsOnly>你可以改变它来满足你的需要。你可以检查这里可用的密钥代码列表。。
希望能帮上忙。
发布于 2016-12-21 23:15:24
您可以通过以下方式使用regex实现这一目标:
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>
https://stackoverflow.com/questions/41271354
复制相似问题