Limit the valid input values for the number within the range of 1 to 3

HTML code

<div class="col-sm-12">
  <input class="form-control form-control-md" [ngModel]="item.threshold" placeholder="Set Threshold" formControlName="threshold"
    type="text">   
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('required') && editThreshold.get('threshold').touched">threshold is required.</span>
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('pattern') && editThreshold.get('threshold').touched">threshold value should be number.</span>
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('maxlength') && editThreshold.get('threshold').touched">maximum three digits.</span>                
</div>

ts code

this.editThreshold = new FormGroup({
  threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]/),Validators.maxLength(3)]),
});

I need to set a restriction in the pattern that only accepts numbers between 1 and 3.

Answer №1

In order to restrict input to only three digits, use the following regular expression: [0-9]{1,3}. This pattern will allow exactly three digits and anything more will fail validation. With this regular expression in place, you may not need the maxlength validator as it is already taken care of.

Implement it like this:

this.editThreshold = new FormGroup({
  threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]{1,3}/)),
});

Answer №2

For a quick solution, utilize the ng2-validation plugin. https://github.com/yuyang041060120/ng2-validation#rangelength

npm install ng2-validation --save

Add it to your app module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CustomFormsModule } from 'ng2-validation'

import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule, FormsModule, CustomFormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {
}

For Template-driven forms

<input type="text" [(ngModel)]="model.field" name="field" #field="ngModel" [rangeLength]="[5, 9]"/>
<p *ngIf="field.errors?.rangeLength">error message</p>

For Model-driven approach

new FormControl('', CustomValidators.rangeLength([5, 9]))

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

How to determine the return type based on the quantity of arguments passed to a rest parameter function

Is there a way to create an arrow function using rest parameters that can return different types based on the number of arguments passed? For example, I am looking to implement a safeId() function with the following return type variations: safeId() // () ...

Activate angular2-notifications using an interceptor

I implemented an interceptor code in my Angular project that displays an alert for API responses, but I would like to replace it with angular2-notifications. Here is a snippet from app.component.html: <router-outlet><app-spinner></app-spin ...

What could be causing Angular to not send cookies in a POST request even after setting withCredentials to true?

After refining the question for clarity, here is the updated version: The original query was: How can I resolve the Angular and Spring Boot configuration with Spring JDBC authentication to enable smooth logout functionality even when CSRF protection is ...

There is a clash between the webpack-dev-server package and its subdependency, the http-proxy-middleware

Awhile back, I integrated webpack-dev-server v3.11.0 into my project, which - upon recent inspection - relies on http-proxy-middleware v0.19.1 as a dependency. Everything was running smoothly until I separately installed the http-proxy-middleware package a ...

Angular 6's inability to subscribe to a subject from multiple components simultaneously is causing issues

Having an issue with data subscription between parent and child components and a service. When emitting data using the next method in the subject class, only the child component receives the data. In navbar.component.ts: this.messageService.setClientUser ...

The continuous rerendering of my component occurs when I use a path parameter

In my project, I am working on utilizing a path parameter as an ID to fetch data for a specific entity. To accomplish this, I have developed a custom data fetching hook that triggers whenever there is a change in the passed parameters. For obtaining the bo ...

I can see my Angular 2 object displayed on the console, however, the specific properties are not showing up in the template

Below is the template and component code snippet that I am working with: Template: <div *ngIf="newJobCreated"> <h3>Name: {{newJob.name}}</h3> <h3>Job: {{newJob.job}}</h3> <h3>ID: {{newJob.id}}&l ...

What is the process for unsubscribing through an HTTP post request within an Angular application

There is a POST API set up through API Gateway on AWS, but it seems to be returning an infinite loop of arrays, as shown in the image below. How can I make it return just one array? Multiple requests Below is the code snippet: Angular import { Componen ...

Adding numbers in Angular2 using ngFor with incremented index

Trying to increase the index value in order to generate a numbered list: 1, 2, 3, 4 <tbody> <tr *ngFor="let item of queue.truckQueus; let i = index" [attr.data-index]="i"> <td>{{i++}}</td> //this results in an error ...

What are the steps for implementing PathLocationStrategy on a local server?

Currently developing an Angular 4 web application and in need of utilizing PathLocationStrategy instead of HashLocationStrategy. The downside to using PathLocationStrategy is that upon refreshing a page, a blank page appears with 404 errors showing up in ...

Getting the URL segment while using a CanActivate guard

Ensuring users authenticate before accessing a requested page using a guard is crucial. In one specific scenario, a user may enter a URL with query parameters like To retrieve both the parameters and the URL segment within the guard, a piece of code has ...

Retrieving updated data from a service does not trigger a refresh of the view

Having an issue with rendering data obtained from a service. Here is the situation: The service retrieves values from a distant API using an Observable: @Injectable() export class myService { constructor(private http: Http) { } getData(listLength: num ...

Mocha has difficulty compiling Typescript code on Windows operating system

In developing my nodejs module, I created several unit tests using Mocha and Chai. While these tests run smoothly on macOS, they encounter compilation issues on Windows, resulting in the following error: D:\projects\antlr4-graps>npm test > ...

Prevent saving the file until all the categories have been chosen

We have recently updated our file list by adding a new file category column. Our aim now is to prevent users from saving the form until a category has been assigned to each file. However, I am unsure how to check for the presence of a value in each file ...

Unable to specify custom header in HttpClient (ionic 3 application with Angular 5)

I'm attempting to utilize an API that requires an 'Auth' key. I am working on sending the key using httpHeaders with the code provided below: getTest(){ let data = {'loginusertype':'12','loginuserid':'51&a ...

What is the significance of including the Angular component selector in HTML?

I'm brand new to Angular and html/html5, so please bear with me if my questions seem basic. I've included a screenshot below: https://i.sstatic.net/UXobT.png Here are the questions on my mind: Q1- The component selector name paproductform is n ...

Unique text: "Singleton React component"

A counter component has been implemented using a npm package available here. import * as React from 'react'; import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core'; import withRoot from '../../../withRoot&a ...

The value of 'e.target.files' could potentially be null

After selecting a file in my input component, I extract its content. The code I used is from this source An error has arisen related to the line onChange={e => handleFileChosen(e.target.files[0])}, specifically highlighting e.target.files. The error m ...

Obtaining the specified cell in a row when a button is clicked

I'm currently grappling with how to retrieve the value of the nth cell in the same row as the button that was clicked in angular2. I understand that I need to pass the $event value, but I'm unsure of how to extract the relevant data. In app.comp ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...