简体   繁体   中英

Allow only numbers in a text input with Angular

I am trying to write code which will allow only numbers in a text input text. I've written the following directive.

import { Directive, ElementRef, Input, HostListener } from '@angular/core'

@Directive({
    selector: '[appAllowNumberonly]'
})
export class AllowNumberonlyDirective {

    private el: HTMLInputElement;

    constructor(private elementRef: ElementRef) {
        this.el = this.elementRef.nativeElement;
    }

    @HostListener("keydown", ["$event"])
    onKeyDown(e: KeyboardEvent) {
        if (this.el.value == undefined) {
            this.el.value = '';
        }
        let transformedInput = this.el.value.replace(/[^0-9]/g, '');
        if (transformedInput != this.el.value) {
            this.el.value = transformedInput;
        }
    }

    @HostListener("keyup", ["$event"])
    onKeyUp(e: KeyboardEvent) {
        if (this.el.value == undefined) {
            this.el.value = '';
            e.preventDefault();
        }
        let transformedInput = this.el.value.replace(/[^0-9]/g, '');
        if (transformedInput != this.el.value) {
            this.el.value = transformedInput;
        }
        return transformedInput;
    }

    @HostListener("blur", ["$event.target.value"])
    onBlur(value) {
        if (this.el.value == undefined) {
            this.el.value = '';
        }
        let transformedInput = this.el.value.replace(/[^0-9]/g, '');
        if (transformedInput != this.el.value) {
            this.el.value = transformedInput;
        }
    }
 }

This works perfectly fine, but user is able to enter value into the text box and then my directive is removing the values that are non-numeric, but I want to stop user from entering into the textbox, how can I achieve that?

I want to cover copy paste scenario with mouse as well.

I have below Plunker which works perfectly fine in AngularJS (1.x), how do I convert to Angular? I am unable to use parsers.

http://jsfiddle.net/thomporter/DwKZh/

I also tried this:

图片

Try this directive. Listen for the input event to also handle copy and paste.

export class NumberOnlyDirective {
  constructor(private el: NgControl) {}

  @HostListener('input', ['$event.target.value'])
  onInput(value: string) {
    // NOTE: use NgControl patchValue to prevent the issue on validation
    this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
  }
}

You can use Ng Knife utility

  1. Import NgKnifeModule

     ... import { NgKnifeModule } from 'ng-knife'; ... @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgKnifeModule ], ... }); export class AppModule { }
  2. Using it:

     <!-- Only Numbers --> <input knifeOnlyNumbers type="text">

your directive code should have this

@HostListener("keypress",['$event']) onKeyPress(e){
        var char=e.char;
        var regExp = new RegExp(/[0-9.]/);
        if (regExp.test(char)) 
            return true
        else
            return false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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