Angular - Creating validations for numeric input fields within reactive forms to ensure values fall within a designated range

One issue I am facing in my Angular form is with a numeric input field. The requirement is to set the minimum value as 3 and the maximum value as 10. However, upon loading the form, the default value should be 0. Users are expected to enter values ranging from 0 to between 3 and 10. Unfortunately, I encountered an error when trying to submit the form with the default value of 0. How can this be resolved?

The structure of the HTML page is outlined below.

<form #ConfigForm="ngForm" [formGroup]="sampleform" (ngSubmit)="onSendHandler()">
    <mat-form-field class="mat-form-field" appearance="outline">
    <input matInput formControlName="numValue"/>
    <mat-error *ngIf="sampleform.get('numValue').hasError('pattern')">Numbers Only ! 
    </mat-error>
    <mat-error *ngIf="sampleform.get('numValue').hasError('min')">Min Value is 
    3</mat-error>
    <mat-error *ngIf="sampleform.get('numValue').hasError('max')">Max Value is 
    10</mat-error>
   </mat-form-field>
</form>

.ts file

//set default values
this.sampleform.patchValue({
  numValue: 0
});

sampleform = new FormGroup({
numValue: new FormControl('', [Validators.pattern("^[0-9]*$"), Validators.min(3), 
Validators.max(10)])
});

Answer №1

To ensure proper validation, it is important to create a custom ValidatorFn that examines the default value and range validators as demonstrated below:

defaultValueOrRangeValidator(
  defaultValue: number,
  ...rangeValidators: ValidatorFn[]
): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value == defaultValue) return null;

    for (let validator of rangeValidators) {
      if (validator(control)) return validator(control);
    }
  };
}
this.sampleform = new FormGroup({
  numValue: new FormControl('', [
    ...
    this.defaultValueOrRangeValidator(
      0,
      Validators.min(3),
      Validators.max(10)
    ),
  ]),
});

Check out the Sample StackBlitz Demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending the chosen dropdown ID to a different component

In my application, there is a component named list where I am showcasing all the names of my customers in a dropdown, as illustrated below: https://i.sstatic.net/KEmAG.png When a particular item (i.e., customer) is selected from the dropdown, I would lik ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Angular 9: Implementing a synchronous *ngFor loop within the HTML page

After receiving a list of subjects from the server, exercises are taken on each subject using the subject.id (from the server) and stored all together in the subEx variable. Classes are listed at the bottom. subjects:Subject[] temp:Exercise[] = [] s ...

What causes the function endpoint to become unreachable when a throw is used?

One practical application of the never type in typescript occurs when a function has an endpoint that is never reached. However, I'm unsure why the throw statement specifically results in this unreachable endpoint. function error(message: string): ne ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Typescript - Conditional imports

When working with the moment-timezone module, one issue that arises is receiving a warning if it is included multiple times. In my specific case, I have a module that necessitates the use of this timezone functionality. Since I am unsure whether or not the ...

Typescript error: The property "Authorization" is not found in the type HeadersInit

As I utilize the npm module node-fetch, I have a helper function specifically designed to facilitate authorized requests to a third-party service. This function essentially acts as middleware by incorporating the Authorization header. async function makeAu ...

Navigating with the Angular router to a child route is causing a redirection to the 404

I'm facing a challenge with navigating to a child component from the parent view. This is how my app-routing configuration looks: const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'fu ...

The Vue and Typescript webpage is not appearing in the GAS sidemenu template

I am tasked with developing an application for Google Sides using Vue + Typescript to enhance its functionality with an extra menu feature. You can find a sample without Typescript here. The result is visible in this screenshot: https://gyazo.com/ed417ddd1 ...

The graph that should appear in Angular2 with ng2-charts is missing

I'm currently working on a project that requires implementing charts using Angular2 (version 2.4.8). I am utilizing ng2-charts (version 1.5.0) and the corresponding version of chart.js is 2.5.0. Initially, I started by copying an example code from the ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...

Error in ng2-pdf-viewer: Invalid parameter object received. Please provide either the .data, .range, or .url parameter

Trying to integrate ng2-pdf-viewer into my Angular 7 project has been a challenge. Initially, I tackled a cors issue by following this advice. However, I am now faced with the error below: Invalid parameter object: need either .data, .range or .url at Obj ...

Issue with sending headers in HttpClient.post method in Angular 8

I have successfully implemented the following code: this.http.post (TGT_IP,body, {responseType: 'arraybuffer'}).subscribe( (val) => { console.log("POST call successful value returned in body", val); ...

Leverage a personalized column within a for loop in an Angular template

I have created the code below: table.component.html <div class="mat-elevation-z8"> <table mat-table [dataSource]="tableDataSrc" matSort class="mat-elevation-z8"> <ng-container *ngFor="let col of tableCols"> <ng-container ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Explanation of Default Export in TypeScript

I recently started learning about JS, TS, and node.js. While exploring https://github.com/santiq/bulletproof-nodejs, I came across a section of code that is a bit confusing to me. I'm hoping someone can help explain a part of the code. In this project ...

I am interested in utilizing angular 4 ng2-ui/map with places-auto-complete functionality that is restricted to a specific country

Check out my code snippet below: <input class="form-control" placeholder="Pickup Location" places-auto-complete (place_changed)="pickupChanged($event)" formControlName="pickup_location" [types]="['geocode']" /> I am trying to figure out ...