如何限制输入文本框仅以Angular2形式输入数字?

时间:2016-12-21 20:26:50

标签: javascript angular angular2-template angular2-forms angular2-services

我必须限制用户只在Angular2->格式的字段中输入数字 我有解决方案,但退格在输入字段中不起作用 任何人都可以有适当的解决方案吗?

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事件中,它限制用户只输入数字,但此代码的问题是退格,标签键不起作用。所以,这段代码不符合我的期望......

8 个答案:

答案 0 :(得分:2)

我做了一个指令来阻止特定的输入,这与此处和其他帖子中发布的其他内容类似。我在this article中建立了我的网站,但进行了一些更改,以避免使用不推荐使用的keyCode属性。

我还取消了对允许的键盘命令(包含CtrlCommandShiftAlt的任何键的限制)的限制,因为这可能会导致意外的限制(例如无法执行undo / redo命令)。

这是指令:

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>

您可以更改它以满足您的需求。您可以check the list of available key codes here

希望有帮助。

答案 1 :(得分:1)

您可以通过以下方式使用正则表达式来实现:

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>

答案 2 :(得分:1)

我创建了一条指令,仅允许您键入数字。

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();
       }
    }
}

然后您可以像这样使用它。

<input matInput app-numeric-field>

答案 3 :(得分:0)

Backspace不起作用,因为:event.charCode不会映射到退格键的其中一个数字0-9

您需要将退格键入白名单(即keyCode = 8)。这样的事情(在我的头顶):

if(event.keyCode != 8 && !pattern.test(inputChar)) {
   event.preventDefault();
}

答案 4 :(得分:0)

我的回答是: - 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);
 }

答案 5 :(得分:0)

如何使用html5标签? <input type="number">
它受到所有浏览器的支持。

https://www.w3schools.com/html/html_form_input_types.asp

答案 6 :(得分:0)

你也可以这样使用

keyPress(event: any) {

        const pattern = /[0-9\+\-\ ]/;
        let inputChar = String.fromCharCode(event.charCode);

            if (!pattern.test(inputChar) && event.charCode != '0') {
                event.preventDefault();
            }
    }

答案 7 :(得分:0)

请不要再使用String.fromCharCode(event.keyCode),它被标记为已弃用MDN,它似乎在Firefox 58中无效。一个简单的功能,在Chrome&amp;火狐:

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();
  }
}

我对这段代码也不满意,希望在Angular中有更好的库。