Search code examples
javascriptangularangular2-templateangular2-formsangular2-services

How to restrict input textbox to enter numbers only in Angular2 form?


I have to restrict user to enter only numbers in a field in Angular2->form I have solution but backspace is not working in input field Can anybody have proper solution for that?

form.html

<input (keypress)="keyPress($event)" minlength="8" maxlength="15" required />

form.component.ts

keyPress(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.charCode);
    // console.log(inputChar, e.charCode);
       if (!pattern.test(inputChar)) {
       // invalid character, prevent input
           event.preventDefault();
      }
 }

On kepress event it restrict user to enter only numbers but problem with this code is backspace, tab keys are not working.So, this code is not as per my expectation...


Solution

  • my answer is :- form.html:

    form.component.ts

    restrictNumeric = function (e) {
         var input;
         if (e.metaKey || e.ctrlKey) {
            return true;
         }
         if (e.which === 32) {
            return false;
         }
         if (e.which === 0) {
            return true;
         }
         if (e.which < 33) {
            return true;
         }
         input = String.fromCharCode(e.which);
         return !!/[\d\s]/.test(input);
     }