0

I have a form in Angular which i want that the user will only submit a full number (not decimal) and he will not have the option to write .(dot) symbol in the form in order to write the decimal number. I want to block completely the option to write .(dot) at the form. Is it possible?

I tried the solution here : Proper way to restrict text input values (e.g. only numbers) Using regex :

In component.ts add this function

_keyUp(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

In your template use the following

<input(keyup)="_keyUp($event)">

But it did not work, the option to write .(dot) at the form is still possible.

I want to block completely the option to write .(dot) at the form.

AT82
  • 71,416
  • 24
  • 140
  • 167
lironzaa
  • 484
  • 2
  • 8
  • 17

2 Answers2

2

I believe the character is already present at the time of the keyup event, and you can't prevent something that has already happened. Try the keypress event:

<input (keypress)="_keyUp($event)">
CDelaney
  • 1,238
  • 4
  • 19
  • 36
1

@CDelaney is correct, but some additional thoughts: This (found) stackblitz I would say does it better:

Component html:

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

and the TS file:

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

Why it's better?

  1. No regex: as the saying goes, if you try to solve a problem with Regex, now you have two problems.

  2. Keypress, it will be closer to what you want without having to replace strings

  3. Better event names. If I had my druthers _namesOfAnything would never be a thing.

Austin T French
  • 5,022
  • 1
  • 22
  • 40