【问题标题】:How to prevent an input field from accepting other numbers than 0 or 1?如何防止输入字段接受除 0 或 1 以外的其他数字?
【发布时间】:2019-09-14 13:12:20
【问题描述】:

我正在构建一个 bin 到 dec 转换器来学习 Angular,但在阻止输入字段接收/显示除 0 或 1 之外的其他数字时遇到了麻烦。

这是我目前所拥有的:

我的组件 html 文件

<form [formGroup]="numberForm">

<input (keyup)="onKey($event)" id="number" placeholder="" value="">
   <button (click)="convert()">Convert</button>
</form>

<div class="output">{{ output }}</div>

我的组件 ts 文件

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';


@Component({
selector: 'app-converter',
templateUrl: './converter.component.html',
styleUrls: ['./converter.component.css']
})

export class ConverterComponent implements OnInit {
numberForm;
values;
output;

constructor(
private formBuilder: FormBuilder
) {

this.numberForm = this.formBuilder.group({
number: ''

})
}

ngOnInit() {}

convert() {
    this.output = parseInt(this.values, 2);
}

onKey(event: any) {
    console.log(event.target.value);
    if((event.keyCode < 48) || (event.keyCode > 49)) {
        alert('Only 1 and 0 please!');
        return false;
    }
this.values = event.target.value;

}
}

这有点像警报消息触发但无效数字仍添加到输入字段,我不知道如何解决这个问题。

我尝试了什么 我曾尝试使用 keyDown 事件,但对于第一次执行,即使我输入了有效数字,console.log(event.target.value) 也会输出 null。

【问题讨论】:

  • 请格式化您的代码。
  • @vulp 这样更好吗?
  • 有点,但还可以更好。

标签: angular


【解决方案1】:

你可以处理input事件:

<input (input)="onInput($event)" ...>

如果您检测到该字段中存在除01 之外的任何字符,则您放回之前的有效值。除了键盘输入外,该方法还考虑粘贴在字段中的文本,并允许使用 Backspace 键、箭头键和其他文本编辑键。

binaryValue = "";

onInput(event: Event) {
  const element = event.target as HTMLInputElement;
  const newValue = element.value;
  if (/[^01]/.test(newValue)) {        // If any character other than 0 or 1 is present
    element.value = this.binaryValue;  // Put back the previous valid value
    alert("Only 1 and 0 please!");
  } else {
    this.binaryValue = newValue;       // Only 0 and 1 are present, accept the new value
  }
}

请参阅this stackblitz 以获取演示。

【讨论】:

    【解决方案2】:

    您需要在返回 false 之前添加event.preventDefault() 以停止事件,并使用keydown 代替keyup 事件。或input 事件,如果使用新浏览器(IE 不支持)

    【讨论】:

    • 具体添加到哪里?在 onKey if 语句中?如果是,那在我仍然可以输入 2,3 或任何其他数字的意义上是行不通的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    相关资源
    最近更新 更多