What is the process for initiating validation on a FormArray?

I have a form with an object containing two 'normal' attributes and one form array. I need to validate whether a field in the object within the form array is a port or a portrange using regex, but the validation is not being displayed (no red input-field or mat-error).

Typescript

this.myForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9._-\s]*$')]],
      description: ['', Validators.maxLength(255)],
      elements: new FormArray([this.createElement()])
    });
...
createElement(): FormGroup {
    return this.fb.group({
      'portRanges': ['', [Validators.required]],
      'protocol': ['',[Validators.required, Validators.pattern('^\d+$|^\d+-\d+$')]]
    });
}
<div formArrayName="elements" *ngFor="let e of elements.controls; let i = index;">
  <div [formGroupName]="i">
    <mat-form-field class="field">
      <input tabindex="3" matInput placeholder="Port or range *" formControlName="portRanges"/>
      <mat-error>Between 0 and 65535, or a range of two such numbers separated by a dash ( - )</mat-error>
    </mat-form-field>

    <mat-radio-group aria-label="Select a protocol" [ngStyle]="getStyle(e)" formControlName="protocol">
      <mat-radio-button value="TCP" tabindex="4">TCP</mat-radio-button>
      <mat-radio-button value="UDP" tabindex="5">UDP</mat-radio-button>
    </mat-radio-group>

    <div style="display: flex">
      <div>
        <div *ngIf="i === elements.controls.length - 1" style="margin-right: 5px;" class="action-btn" tabindex="6" (click)="addBlankElement()">
          <i class="material-icons">add_circle</i>
        </div>
      </div>
      <div *ngIf="elements.length > 1" class="action-btn remove-btn" tabindex="7" (click)="removeElement(i)">
        <i class="material-icons">remove_circle</i>
      </div>
    </div>
  </div>
</div>

Solved by validating all elements after value changes:

ngOnInit(){
  this.createForm();
  this.myForm.valueChanges.subscribe((data) => {
    this.validate(this.myForm);
  })
}

validate(group: FormGroup = this.myForm){
  this.elements.controls.forEach((data) => {
    data.updateValueAndValidity();
  })
}

Answer №1

To ensure the validation is updated in this scenario, make sure to utilize updateValueAndValidity:

this.myForm.get('name').updateValueAndValidity();
this.myForm.get('description').updateValueAndValidity();

Afterwards, call

this.myForm.updateValueAndValidity();

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

Monitor the status of your Angular CLI build with real-time notifications

Encountered an interesting issue while trying to integrate the 'webpack-notifier' plugin into a new Angular 7 application. The goal was to have balloon notifications for build failures when running 'ng build --watch' in the console. TL ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

Roundabout Navigation Styles with CSS and jQuery

My goal is to implement a corner circle menu, similar to the one shown in the image below: https://i.stack.imgur.com/zma5U.png This is what I have accomplished so far: $(".menu").click(function(){ $(".menu-items").fadeToggle(); }); html,body{ colo ...

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

If the item with the specified name is not found in the list, display an image using Vue's v-if directive

<ul class="ulItems" v-for="item in listingItems" :key="item.channels"> <li class="liItems"> {{ item.itemName }} </li> </ul> I am looking to incorporate an image in situations where th ...

Issues with the parseInt() Function

I'm having trouble figuring out why parseInt() isn't working correctly in my code, especially when passing numbers through to my function parameters. It keeps returning NaN in both my array and the function's return value. What I'm att ...

"Node.js mystery: Why does a function call return undefined, only to be evaluated

Utilizing the async module, I am running a series of functions in parallel. However, I have encountered an issue where the return value of another function is undefined because the callback does not wait for it to be evaluated. function getGenresId(genres ...

JavaScript Arithmetic Expressions

My experience with Java and PHP spans many years, and I have recently delved into JavaScript development as well. This may be a beginner question but can someone help me figure out why this application isn't displaying the interest when the button is ...

Leverage React Native elements within a Meteor React-based website

Currently, we are in the process of developing a Meteor React web application that will be displayed within a web view on a react native app. While this arrangement may seem unconventional, it is due to time constraints and the fact that the react native a ...

I'm trying to figure out how to incorporate this code into an arrow function while also utilizing the iterating array element

I am aiming to create a function that can provide either true or false based on whether the searchElement exists in the array. While I could achieve this with a simple for loop and if-else statement, my goal is to utilize an arrow function. Although JavaS ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Bring in d3 along with d3-force-attract

Recently, I have installed D3 along with d3-force-attract. npm install @types/d3 -S npm install -S d3-force-attract I am currently facing an issue with importing d3 force attract as it is not recognized as a typescript module, unlike d3 itself. The inco ...

What are some examples of utilizing paths within the tsconfig.json file?

Exploring the concept of path-mapping within the tsconfig.json file led me to the idea of utilizing it to streamline cumbersome path references: https://i.sstatic.net/AYmv4.png The project layout is unconventional due to its placement in a mono-repositor ...

Creating a unique custom authentication controller in Strapi.OR

While using Strapi for my API and Back office, I've encountered a problem. Everything works fine except for one issue: I am struggling to override the controller used for the forgot password feature. Despite attempting to follow the documentation, par ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Exploring trees with jQuery: A guide to traversal techniques

<ul id="org" style="display:none"> <li id="visited"><a href="#" class="ui-link">ROOT</a> <ul id="main_child_ul" class="children"> <li><a href="#">Acura</a> & ...

Decoding multiple data with jQuery on the server-side

Scenario: A situation arises where I am utilizing a jQuery.ajax call to send three arrays to the server for database storage. The challenge lies in decoding the combined data object on the server side and breaking it back into the original three arrays. ...

Automatically launch a popup window specified in JavaScript

Aim:- I am trying to automatically open a radwindow from the server-side based on a specific IF condition. Snippet Used:- In the aspx page, I have defined the radwindow as follows: <telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal= ...

Transitioning to Firebase Authentication

I made the decision to transition away from firebase authentication. To accomplish this, I exported all firebase users along with their email addresses, hashed passwords, salt keys, and other necessary information. Next, I transferred them to a database a ...

What is the process of defining a group of particles in relation to a vector path using Three.js?

In my exploration of Three.js, I have been experimenting with particle clouds and their unique properties. Many examples I have come across utilize shape geometries to generate fields of particles or random parameters for their distribution. However, I a ...