0

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.

1
  • please share the code if possible a stackblitz Commented Dec 11, 2023 at 5:19

1 Answer 1

1

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

2
  • I already went down this route. I wasn't able to restrict input on paste. I kept running into hurdles with that. It's not acceptable to disallow Paste in my application. Commented Dec 11, 2023 at 5:44
  • @arunkumaraqm please share the challenges, to take it forward, angular returns null when I type e, it will be difficult to validate this! Commented Dec 11, 2023 at 6:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.