Show validation error when dot or e is typed in to input type=number

I have an input type=number for a Percentage field. I only want the user to enter a number between 0 and 100. I want to disallow any decimal values such as 50.25, 60.2, 70.0. I also want to disallow any usage of exponents such as 2e1, 1e2.

I have tried creating a custom validator but Angular converts 10.0 to 10 and 2e1 to 20 so I am not able to validate control.value.

  • please share the code if possible a stackblitz

    – 

Restrict the input of the user, so that you wont have this problem, also add the Validators.max and Validators.min to show errors when the limit is exceeded!

import { JsonPipe } from '@angular/common';
import { Component } from '@angular/core';
import {
  FormControl,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule, ReactiveFormsModule, JsonPipe],
  template: `
  <form [formGroup]="formGroup">
    <input name="num"  id="num" formControlName="num"
      type="number"
      min="1"
      max="100"
      step="1"
      onkeypress="return event.charCode >= 48 && event.charCode <= 57"
      title="Numbers only">
      {{formGroup.controls['num'].errors | json}}
</form>
  `,
})
export class App {
  name="Angular";
  formGroup: FormGroup<any> = new FormGroup({});

  ngOnInit() {
    this.formGroup = new FormGroup({
      num: new FormControl(1, [Validators.min(1), Validators.max(100)]),
    });
  }
}

bootstrapApplication(App);

stackblitz

Leave a Comment