Angular validation is malfunctioning for fields that have names ending with periods

Currently in the process of generating dynamic input fields

<input class="form-control-lg form-control" placeholder="{{data.DisplayName}}" formControlName="{{data.labelName}}" type="text"  maxlength="13">

As I iterate through 'fieldsData' array elements, a new FormControl is created for each with specific conditions set based on certain criteria:
this.fieldsData.forEach((ele, i) => {
  form[ele?.labelName]=new FormControl('',ele?.mandatory=='yes' ? Validators.required : []);
  this.FormGroup=new FormGroup(form);
..
}

An issue arises on my HTML component where an error message does not display as expected. This is specifically related to field name validation and the presence of a dot at the end.

<div *ngIf="FormGroup.get(data.labelName) as control"> <div *ngIf="(control.touched || control.dirty) && (!control.valid)"> <p class="errorMsg" *ngIf="control.errors.required">This field is required</p>  <p class="errorMsg" *ngIf="control.errors.pattern">Please provide a valid email address</p>     </div> </div>

The challenge lies in ensuring that when there is a dot at the end of the field name, both validation and error messaging function correctly.

Answer №1

To resolve this issue, consider using an alternative approach to access the control instead of encountering errors with the dot notation. One potential solution is to utilize dynamic access methods by using controls in place of getControl.

getControl(labelName: string) {
  return this.FormGroup.controls[labelName];
}

Complete Code:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  FormBuilder,
  ReactiveFormsModule,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import 'zone.js';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  template: `
    <form [formGroup]="FormGroup">
            <div *ngFor="let data of fieldsData">
            <ng-container [ngSwitch]="data.inputType">
              <ng-container *ngSwitchCase="'dropdown'">
                <select name="cars" id="cars">
                  <option value="volvo">Volvo</option>
                  <option value="saab">Saab</option>
                  <option value="mercedes">Mercedes</option>
                  <option value="audi">Audi</option>
                </select>
              </ng-container>
              <ng-container *ngSwitchCase="'textbox'"><textarea [formControlName]="data.labelName"></textarea></ng-container>
              <ng-container *ngSwitchDefault><input type="text" [formControlName]="data.labelName"></ng-container>
            
              


            </ng-container>
            <div *ngIf="FormGroup.get(data.labelName) as control" class="checkValue"> <div *ngIf="(control.touched || control.dirty) && (!control.valid)"> <p class="errorMsg" *ngIf="control.errors?.['required']">This field is required</p>  <p class="errorMsg" *ngIf="control.errors.pattern">Please provide a valid email address</p>     </div> </div>
            <label>{{data.labelName}} </label>
            
            </div>
            <button class="btn-submit" type="button" [disabled]="!FormGroup.valid" style="margin-top: 20px" (click)="SubmitDemo()">
                Submit
            </button>
    </form>
  `,
})
export class App {
  fieldsData = [
    {
      labelName: 'Name',
      inputType: 'textbox',
      inputValues: '',
      mandatory: 'yes',
    },
    {
      labelName: 'contact no.',
      inputType: 'textbox',
      inputValues: '',
      mandatory: 'yes',
    },
    {
      labelName: 'address 2',
      inputType: 'textarea',
      inputValues: null,
      mandatory: 'yes',
    },
  
  ];
  FormGroup!: FormGroup;

  ngOnInit() {
    const form: any = {};
    this.fieldsData.forEach((ele, i) => {
      const validators = ele?.mandatory === 'yes' ? [Validators.required] : [];
      form[ele?.labelName] = new FormControl('', validators);
    });
    this.FormGroup = new FormGroup(form);
  }

  SubmitDemo() {}
}

bootstrapApplication(App);

Check out the Stackblitz Demo for more information!

Answer №2

To prevent any issues with variable names ending in dots, use bracketed notation as shown below:

<div *ngIf="FormGroup.get(data.labelName) as control">
  <div *ngIf="(control.touched || control.dirty) && (!control.valid)">
    <p class="errorMsg" *ngIf="control.errors?.required">This field is required</p>
    <p class="errorMsg" *ngIf="control.errors?.pattern">Please provide a valid email address</p>
  </div>
</div>

Considering you are utilizing a reactive forms-driven approach in Angular, use FormControlName instead of name in HTML using square bracketed notation like this:

<input class="form-control-lg form-control" 
   placeholder="{{data.DisplayName}}" 
   [formControlName]="data.labelName" 
   type="text" 
   maxlength="13">

Then proceed with the respective component.ts setup as demonstrated below :

this.fieldsData.forEach((ele, i) => {
  form[ele?.labelName] = new FormControl('', ele?.mandatory == 'yes' ? Validators.required : []);
});
this.FormGroup = new FormGroup(form);

Answer №3

Why in the world would you want to create a form with properties that end in dots?

You will be getting yourself into trouble early on.

My suggestion is to add a new property, such as "name," and use something like

dataExtends=this.fieldsData.map((x:any)=>
  ({...x,
    name:x.labelName.replace(/[ |\.]/g,'')
  }))

Then use dataExtends instead of data

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

Importing components with local data within an ngFor in Angular TypeScript

Having recently started working with Angular2, I am facing a challenge with importing components in ngFor loops. The issue seems to arise when importing components with data in ngFor loops; it checks for values in the .ts file instead of the local variabl ...

Error encountered when creating a new project using ASP.NET Core (.NET 5) and Angular 11

When I start a new ASP.NET Core Web API + Angular project in Visual Studio by using: dotnet new angular, it sets up a .NET 5 project with an Angular 8.2 project in the ClientApp folder. After hitting F5, everything runs smoothly. However, I want to work ...

Angular 4 - dealing with request timeouts

I am having trouble implementing a request every second in my code as the timeout function is not working correctly. matchlist.service.ts import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/timeout'; getMatch(matchId: num ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

Will other functions in the file run if only a single function is imported?

The file bmiCalculator.ts contains the following code: import { isNotNumber } from './utils'; export default function calculateBmi(height: number, weight: number) { const bmi = weight / Math.pow(height / 100, 2); if (bmi < 18.5) { re ...

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

TypeScript was looking for 'never' but found an intersection instead

Can someone help me understand why a conflicting type intersection did not produce a type of never? What am I overlooking? type A = {value: string} type B = {value: number} type D = A & B type E<T> = T extends never ? 'never' : ' ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

Mapping a response object to a Type interface with multiple Type Interfaces in Angular 7: A step-by-step guide

Here is the interface structure I am working with: export interface ObjLookup { owner?: IObjOwner; contacts?: IOwnerContacts[]; location?: IOwnerLocation; } This includes the following interfaces as well: export interface IObjOwner { las ...

Strategies for resolving the TypeScript error code TS7009?

I am currently new to Typescript programming and in the learning phase. I encountered a problem while coding and received an error in the backend console. Here is the code snippet that caused the error: function employee(id:number,name:string) { this.i ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

What is the location for adjusting the angular strictness flags that determine the level of strictness for strictTemplates?

Currently in the process of transitioning our application to strictTemplates, we are encountering a multitude of errors, some more significant than others. As a result, I decided to adjust the strictness of the angular type checker and came across these s ...

Unable to locate the name 'require' in ANGULAR 2 environment

I am working on an Angular2 application that requires integration with a payment API. https://stripe.com/docs/quickstart When following the code sample in the Node.js section from the provided link, the instructions suggest using the following code struc ...

Chromium browser experiencing issues with the functionality of Dropdown component

My issue involves a basic pie chart with a dropdown menu (created with the <select> tag) that allows users to change the data displayed on the chart. I have implemented this in Angular 6 and it works perfectly fine in Firefox. However, when I tested ...

A TypeScript Class that Refers to Itself

I need help with representing a JSON object in an Angular2 typescript class. The JSON object contains an array of objects of its own type. Here is what the JSON object looks like: { "data": { "id": 5, "type": "taxons", "attributes": { ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png I am curre ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Unable to retrieve a substring value in Angular using Typescript

html <p> <input type="text" maxlength="40" (input)="recipientReference = deleteSpacing(recipientReference)" [(ngModel)]="recipientReference" style="width: 30vw; padding: 5px;border: 1px solid;border ...