简体   繁体   English

Angular 8 验证器,用于输入类型号

[英]Angular 8 validator for input with type number

I have an input with a type number which allows by default the insert of some characters like '+' '-' '.'我有一个类型号的输入,默认情况下允许插入一些字符,如'+''-''。

HTML HTML

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

TypeScript 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}')]],

    })
  }

I want to implement a logic which accept only numbers without '+' '-' '.'我想实现一个只接受没有'+''-''的数字的逻辑。

Note: it is mandatory to use number as type of the input注意:必须使用数字作为输入类型

You can register to the keypress event to ignore characters you do not want like the + character.您可以注册到keypress事件以忽略您不想要的字符,例如+字符。 This might also be more user friendly because there is no error message displayed, it just stops the character from being added to the input.这也可能对用户更友好,因为没有显示错误消息,它只是阻止将字符添加到输入中。

<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"/>

The charCode is the ASCII character used. charCode是使用的ASCII 字符 This will allow numbers as well as ENTER and BackSpace.这将允许数字以及 ENTER 和 BackSpace。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM