Angular2 - Input Field To Accept Only Numbers

2019-01-08 05:57发布

In Angular2, how can I mask an input field(textbox) such that it accepts only numbers and not alphabets?

I have the following HTML input:

<input type="text" *ngSwitchDefault class="form-control" (change)="onInputChange()" [(ngModel)]="config.Value" focus)="handleFocus($event)" (blur)="handleBlur($event)"/>

The above input is a generic text input which may either be used as a simple text field or as a numeric field, (for example to show the Year).

Using angular2, how can I use the same input control and apply some sort of filter/mask on this field, such that it accepts only numbers? What are the different ways I can achieve this?

Note: I need to achieve this using only textbox and not using input number type.

21条回答
相关推荐>>
2楼-- · 2019-01-08 06:46

You can create this Validator and import it in your component.
Basically validates the form input string:

  • check there is no dot
  • converts string to number
  • check is an integer
  • check is greater than zero

To implement it in your project:

  1. suggested path in your app folder: src/app/validators/number.validator.ts
  2. import in your component

    import { NumberValidator } from '../../validators/number.validator';

  3. add it to the form control
    inputNumber: ['', [NumberValidator.isInteger]],
  4. if you dont want to show the invalid char, bind a (change)="deleteCharIfInvalid()" to the input, if form.get('inputNumber').hasError('isInteger') is true, delete the last char inserted.
// FILE: src/app/validators/number.validator.ts

import { FormControl } from '@angular/forms';

export interface ValidationResult {
    [key: string]: boolean;
}

export class NumberValidator {

    public static isInteger(control: FormControl): ValidationResult {
        // check if string has a dot
        let hasDot:boolean = control.value.indexOf('.') >= 0 ? true : false;
        // convert string to number
        let number:number = Math.floor(control.value);
        // get result of isInteger()
        let integer:boolean = Number.isInteger(number);
        // validate conditions 
        let valid:boolean = !hasDot && integer && number>0;
        console.log('isInteger > valid', hasDot, number, valid);
        if (!valid) {
            return { isInteger: true };
        }
        return null;
    }        
}
查看更多
该账号已被封号
3楼-- · 2019-01-08 06:47

If you don't want a directive

https://stackblitz.com/edit/numeric-only

in component.html

<input (keypress)="numberOnly($event)" type="text">

in component.ts

export class AppComponent {

  numberOnly(event): boolean {
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;

  }
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-08 06:48

I would like to build on the answer given by @omeralper , which in my opinion provided a good foundation for a solid solution.

What I am proposing is a simplified and up to date version with the latest web standards. It is important to note that event.keycode is removed from the web standards, and future browser updates might not support it anymore. See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Furthermore, the method

String.fromCharCode(e.keyCode);

does not guarantee that the keyCode pertaining to the key being pressed by the user maps to the expected letter as identified on the user's keyboard, since different keyboard configurations will result in a particular keycode different characters. Using this will introduce bugs which are difficult to identify, and can easily break the functionality for certain users. Rather I'm proposing the use of event.key, see docs here https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Furthermore, we only want that the resultant output is a valid decimal. This means that the numbers 1, 11.2, 5000.2341234 should be accepted, but the value 1.1.2 should not be accepted.

Note that in my solution i'm excluding cut, copy and paste functionality since it open windows for bugs, especially when people paste unwanted text in associated fields. That would required a cleanup process on a keyup handler; which isn't the scope of this thread.

Here is the solution i'm proposing.

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

@Directive({
    selector: '[myNumberOnly]'
})
export class NumberOnlyDirective {
    // Allow decimal numbers. The \. is only allowed once to occur
    private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

    // Allow key codes for special events. Reflect :
    // Backspace, tab, end, home
    private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home' ];

    constructor(private el: ElementRef) {
    }

    @HostListener('keydown', [ '$event' ])
    onKeyDown(event: KeyboardEvent) {
        // Allow Backspace, tab, end, and home keys
        if (this.specialKeys.indexOf(event.key) !== -1) {
            return;
        }

        // Do not use event.keycode this is deprecated.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
        let current: string = this.el.nativeElement.value;
        // We need this because the current value on the DOM element
        // is not yet updated with the value from this event
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex)) {
            event.preventDefault();
        }
    }
}
查看更多
登录 后发表回答