Reactive Forms Not Displaying Error for MinLength Validation

I am working with the ReactiveForms module in my Angular application. I have a requirement where an error message should be displayed if the user enters less than 7 numbers, but currently this feature is not functioning as expected. If anyone knows of a solution or workaround, please provide assistance. Thank you.

Service.ts

PhoneNo: ['', [Validators.required, Validators.minLength(7)]],

html

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *" />
        <img src="../../../../assets/img/required-img.png" class="required-img"
          *ngIf="service.formModel.get('PhoneNo').touched && service.formModel.get('PhoneNo').errors?.required"
          title="This fields is mandatory" data-toggle="tooltip" />
          <label *ngIf="service.formModel.get('PhoneNo').touched && service.formModel.get('PhoneNo').errors?.minLength">Minimum 7 characters required</label>

Answer №1

Angular can be a bit confusing when it comes to setting validators within components. Typically, you would set validators like this:

[Validators.minLength(2)]

You might assume that accessing the errors for minLength validation would look like this:

errors?.minLength

But for some reason, Angular uses a different format in templates:

errors?.minlength

To make it work, simply replace the uppercase "L" with a lowercase "l".

Answer №2

You must have at least 9 characters.

User input error: use 'minlength' instead of 'minLength'

Answer №3

In your HTML, you have the maxLength attribute which needs to be removed.

Instead of

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *" maxlength="7" />

Do this

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *" >

Additionally, make sure that <input> and <img> do not have closing tags like <img/>, but instead use <img>.

Instead of using both minLength and maxLength together, consider creating a regular expression for validation:

PhoneNo: ['', [Validators.required, Validators.pattern(^[\s\S]{7}$)]],

Also remember to utilize

service.formModel.get('PhoneNo').errors?.pattern
instead of .errors?.minLength to display the label correctly.

UPDATE @malbarmawi created a helpful demo here: https://stackblitz.com/edit/angular-forms-pattern-bernj2. He also offers an alternative solution to address the same issue.

Answer №4

Implement maxLength validators to limit the number of characters entered to 7 👇

PhoneNumber: ['', [Validators.required, Validators.maxLength(7), Validators.minLength(7)]],

Check out the demo 🔥🔥

Answer №5

One of the reasons it may not be functioning properly is because you need to use maxlength in all lowercase, rather than camelcase. The same rule applies for minlength

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

Discover how to extract a specific piece of data from a JSON file using Angular 2+ framework

I've been working on a code that parses JSON data and populates a table using ngFor. Here's an example of what the output looks like: https://i.sstatic.net/xDlOa.jpg So far, I've successfully listed the data in the table. But now, I&apos ...

Guide on tracking the cursor using Angular

Recently, I developed a basic application in Angular that incorporates animations. You can check out the StackBlitz here to see it in action. The app features states that we can switch to control where an eye is looking. Currently, I am looking for a way ...

Ways to send a callback function to a component?

Looking to create a versatile input box with a dropdown form control feature. The goal is when the user types in 3 or more characters, an API call should be made with the current input value to retrieve an array of strings containing the searched term and ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Handling a callback after the completion of another action in Angular 2

I am facing an issue where I need to delete an item from a list and then update the page to reflect that change. The current code handles the deletion of the item using DELETE_APPLICATION and then fetches the updated list using GET_INSIGHT_APPLICATIONS. Ho ...

Is it possible to utilize MongooseArray.prototype.pull() in typescript?

A problem has arisen in Typescript at this specific line of code: user.posts.pull(postId); An error message I'm encountering states: Property 'pull' does not exist on type 'PostDoc[]' The issue seems to be related to the fac ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

Ways to update the state of an array without clearing the existing array items

I am attempting to add fetched array items to an existing state that already contains items (with plans to include pagination). However, when I try using code similar to setMovies((prevMovies) => [...prevMovies, ...arr1]), I encounter a Typescript erro ...

How can I programmatically close an inner modal that is located in a different component in Angular?

The "customers" component serves as the parent component and is associated with the "customer-page" component as its child. Within the parent component, there is a modal that calls the child component. The child component contains two additional modals th ...

Retrieve events from database within angular-calendar

My challenge lies in loading events from the database onto my calendar view using angular-calendar. I have created an API that returns resources, but I am struggling to bind them onto CalendarEvents. Here is the part where I am attempting to do so: https:/ ...

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

Angular component loading prior to app.component initialization

I decided to inject the userService in the app component so that the service is not empty when injected into other components throughout my app. However, I am encountering an issue where the component loads before the app.component and as a result, my user ...

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

Adding a dynamic CSS stylesheet at runtime with the power of Angular and Ionic 2

Currently, I am working on creating a bilingual application using Ionic2. The two languages supported are English and Arabic. As part of this project, I have created separate CSS files for each language - english.css and arabic.css. In order to switch be ...

Neglecting flatMap errors when utilizing RXJS

I'm currently exploring the use of flatmap to execute multiple parallel requests. However, I've encountered an issue where if one of the requests returns a 404 error, it breaks the entire chain and cancels all remaining requests. Is there a way t ...

Efficiently loading data in a table with a universal filter feature using Angular with PrimeNG

Recently, I managed to set up a datatable with the functionalities of both Lazy loading and global filter. Utilizing PrimeNG components for this implementation was a breeze. However, an issue surfaced where the global filter ceased to function when lazy lo ...

Extracting information from an object retrieved through an http.get response can be accomplished by utilizing various methods and

I am working with an API that returns a JSON object like this: { "triggerCount": { "ignition_state_off": 16, "ignition_state_on": 14, "exit_an_area": 12, "enter_an_area": 19, "door_unlocked": 1, "door_l ...

Obtain an Observable by subscribing with RxJS

My current situation involves a service that makes an HTTP request to an API in order to fetch data. I have some specific logic that needs to be implemented on the observable within the service, while still allowing for subscription to the Observable in my ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Issues with regular expressions occurring within an Angular 2+ Pipe and Reactive Form

In my current setup, I have the following components: The Template: <form [formGroup]="myForm"> <input formControlName="amount" placeholder="Amount"> </form> The Component: import { Component, OnInit, HostListener } from '@angu ...