Exploring FormArray Validation in Angular 6

Managing around 50 controls on my page, especially when it comes to validation, is a bit overwhelming. I find myself repeating the same Validators for each control.

I'm considering grouping the validators into two categories:

1. [Validators.required, Validators.maxLength(50)]
2. Validators.required

However, using the standard validation method makes my code lengthy. Is there a way I can utilize 2 FormArray to organize the controls and apply validations?

this.candidateForm = new FormGroup({
      firstName: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      lastName: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      fatherName: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      motherName: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      placeOfBirth: new FormControl('', Validators.required),
      nationalityList: new FormControl('', Validators.required),
      dateOfBirth: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      genderList: new FormControl('', Validators.required),
});

Is there a way to make this code more readable?

For instance,


FormArray[] values = formControl{ control1, control2, control3};
FormArray[] values2 = formControl{ control4, control5, control6};

validation1 = [Validators.required, Validators.maxLength(50)]
validation2 = [Validators.required]

values = Validation1
values2 = Validation2

This approach would simplify adding additional controls in the future.

Answer №1

One approach would be to define a reusable function as follows:

function generateFormValidator(maximumLength: number = 0) {
  const validationRules = [Validators.required];
  if (maximumLength > 0) validationRules.push(Validators.maxLength(maximumLength));
  return new FormControl('', validationRules)
}

You can then utilize this function in your code like so:

const MAX_LENGTH = 50;
this.userForm = new FormGroup({
      first_name: generateFormValidator(MAX_LENGTH),
      last_name: generateFormValidator(MAX_LENGTH),
      ...
      country_of_birth: generateFormValidator(),

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

Incorporating a <script> tag in Angular 8 to reference an external JavaScript file from a different website

I am currently using Angular 8 and its CLI to develop my website. Issue: I need to include an external JavaScript file from a different website by adding a <script> tag, for example: <script src="https://www.wiris.net/demo/plugins/app/WIRISplugin ...

The Angular project encounters a failure when attempting to run 'ng serve,' resulting in an emitted 'error' event on the worker

Resolved Issue - Update: It appears that the problem was due to an error in my CSS code: Previous: .title & .smaller { color: $dark-blue; font-family: "Roboto"; font-size: 20px; font-weight: 600; width: fit-content; margin: 0; ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

Issue with utilizing Lodash's _.findIndex method while installing lodash through tsd and saving it in an Angular2 project

I have successfully incorporated lodash in two different methods: Method 1: I installed it in bower_component and added declare var _:any; in components. It's working perfectly. Within a click event, I am calling this function: checkLodash() { _.f ...

Calculating the minimum value of a number in Angular 8

I attempted to convert a decimal number to a whole number and encountered an issue. When using the angular pipe method {{myNumber | number: '1.0-0.'}}, it provides a rounded off value instead of the floor value. For example, with number = 3.8, ...

typescript code: transforming object values into keys in typescript

Here is a scenario: const obj1 = { a: 'x', b: 'y', c: 'z', } I am looking to automatically create a type like this: type Type = { x: number, y: number, z: number, } I initially considered the following approach: ...

Exploring the Global Reach of Angular 9

I have been working on updating our current app to implement internationalization using the new approach in Angular 9. Below is how I set it up in the angular.json file: { ... "projects": { "viewer": { ... "i18n": { "sourceLocale": ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

Angular: Intercepting an HttpResponse to trigger additional calls before passing the response back to the caller

My current objective is to intercept a response and, if a certain value (CHALLENGE) is present, trigger a call to another API. I need to retry this process 3 times if necessary. Upon success, I should respond to the initial call and pass the result back to ...

Tips for individually assigning Fastify decorators within various plugins?

I'm encountering issues with typing decorators in two separate plugins (scopes): import Fastify, { FastifyInstance } from 'fastify' const fastify = Fastify() // scope A fastify.register((instance) => { instance.decorate('utilA&apo ...

What is the best way to terminate a connection in @aspnet/signalr?

My project utilizes the dependency "@aspnet/signalr": "^1.1.4". Does anyone know how to properly close a connection in Angular's destructor? I attempted to use: this.connection.close(); ...

What is the best way to extract information from an observable stream?

Within my codebase, there exists an observable that I have defined as: public selectedObjectsIds$ = of(); In addition, there is another stream present: this.reportMode$.pipe( filter((state: ReportMode) => state === ReportMode.close) ) .subscribe(() ...

The dynamic dropdowns in FormArray are experiencing issues with loading data correctly

Having trouble fetching data for selected country states using FormArray Index. The API keeps getting called every time the country code is passed to retrieve the data. Here's what I've tried, <form [formGroup]='formName'> ...

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

CSS code for a fixed fullscreen menu with scrolling

I have implemented a full-screen menu that covers the entire screen, excluding the header and menu tab bar. You can view it here: https://i.stack.imgur.com/h5cQa.png On smaller screens, the entire menu cannot be displayed at once, as shown here: https://i. ...

Using a configuration file with the JavaScriptServices React-Redux template

I have come across this question many times on different platforms, but I haven't been able to make it work for me. The issue is that I am using an API within a React component (with TypeScript 2.4.1 and webpack 2.5.1): .... fetch("some/url/api/", me ...

How can we remove a dynamic component in Angular?

Here is the HTML template for a modal component: <div class="modal"> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"> <button (click)=&q ...

What is the purpose of RouterLink and RouterOutlet in Angular?

RouterLink and RouterOutlet are both angular attribute directives that assist in navigating to a specific route from the collection of routes. Once a matching route is found, the corresponding component is loaded, and its template is rendered on the browse ...

Can I include a different website within an Angular project?

I've recently completed an Angular project and now want to embed a page within another Angular page. Specifically, I'm looking to include www.yahoo.com in my Angular application. ...