【问题标题】:Angular 8 validator for input with type number用于输入类型号的 Angular 8 验证器
【发布时间】:2020-07-20 04:30:50
【问题描述】:

我有一个类型号的输入,默认情况下允许插入一些字符,如“+”“-”“。”

HTML

   <input   type="number"
              class="form-control"
              formControlName="numberChildren"/>

TypeScript

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createForm();
  }

  private createForm(): void {
    this.personalForm= this.formBuilder.group({
        numberChildren: [null, [Validators.required, Validators.pattern('[0-9]{2}')]],

    })
  }

我想实现一个只接受没有'+' '-' '的数字的逻辑。'

注意:必须使用数字作为输入的类型

【问题讨论】:

  • accept only number 在这里不起作用验证器只是测试该值是否正常????
  • Note: it is mandatory to use number as type of the input ← 为什么?
  • 检查这个库 ???? github.com/JsDaddy/ngx-mask
  • @Igor,最终用户希望输入只允许输入数字值。
  • The end-user expect to have inputs that allow only the typing of values numeric ← 你指的是触摸屏(手机/平板电脑)和弹出的键盘吗?也许有一种方法可以默认使用数字键组(0-9 和符号)而不是 QWERTY 键盘。

标签: javascript regex angular typescript angular-reactive-forms


【解决方案1】:

您可以注册keypress 事件以忽略您不想要的字符,例如+ 字符。这也可能对用户更友好,因为没有显示错误消息,它只是阻止将字符添加到输入中。

<input type="number"
  class="form-control"
  (keypress)="($event.charCode === 8 || $event.charCode === 0 || $event.charCode === 13) ? null : $event.charCode >= 48 && $event.charCode <= 57"
  formControlName="numberChildren"/>

charCode 是使用的ASCII character。这将允许数字以及 ENTER 和 BackSpace。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多