Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form

const textBox = {
  fontColor: 'blue',
  fontSize: '18',
  placeholder: 'email',
  name: 'input email',
  label: 'john',
  validation: {
    required: false
  }
};

I developed a dynamic form but now I want to assign validators to each form control

ngOnInit(): void {
  const formDataObject = {} as any;
  for (const key of Object.keys(this.InputObj)) {
    debugger;
    if (key !== 'validation') {
      formDataObject[key] = new FormControl(this.InputObj[key]);
      this.formControls.push(key);
    }
  }
  this.form = new FormGroup(formDataObject);
}

I am looking to add validation rules to the form controls, but some objects may not require any validations

Answer №1

If you're looking to implement validation only when the required property within your validation object is true, follow these steps:

To begin, create a new instance of FormControl, and then utilize the addValidators method for dynamic validation addition:

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

const textBoxes = [
  {
    fontColor: 'red',
    fontSize: '20',
    placeholder: 'name',
    name: 'input name',
    label: 'mohamed',
    validation: {
      required: true,
    },
  },
];

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public form = new FormGroup({});
  ngOnInit(): void {
    for (const textbox of textBoxes) {
      const control = new FormControl(textbox.placeholder);
      if(textbox.validation.required){
        control.addValidators(Validators.required);
      }
      this.form.addControl(textbox.name, control);
    }
  }
}

Visit Stacblitz for demo

Answer №2

// This is a sample component code

  ngOnInit() {

const textBoxes = [
  {
    fontColor: 'red',
    fontSize: '20',
    placeholder: 'name',
    name: 'input name',
    label: 'mohamed',
    validation: [
      required: true,
      min: 5,
    ],
  },
];

    this.initializeForm(textBoxes);
  }    

  initializeForm(controls: YourModel[]) {
    this.formGroup = this.service.createFormGroup(controls);
  }

// It's recommended to use a service for your functionality

  validatorsMap = {
    required: () => Validators.required,
    min: (num: number) => Validators.min(num),
    ... etc: etc(),
    ... etc: etc(),
  };


  createFormGroup(inputs: YourModel[]): FormGroup {

      const group: any = {};

      inputs.forEach(input => {

          const validations: any[] = this.getValidators(input);

          group[input.name] = new FormControl(
            '', // initial value
            validations// custom validations here
          );
        });

      return new FormGroup(group);

  }

  getValidators(input: ControlModel) {

    return input.validation
      .map(validation => {
        return fn = this.validatorsMap[validation.name];
      });
  }

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

Wondering how to optimize FullCalendar for mobile and touch events?

I am looking to incorporate a drop event feature into the mobile version of fullcalendar. To achieve this, I am utilizing Jquery UI Touch Punch. After researching on various platforms such as Stack Overflow 1, Stack Overflow 2, Stack Overflow 3, Stack Ove ...

Upgrading Angular causes issues with fileReplacements not functioning properly for assets

Since upgrading Angular, I have encountered an issue where fileReplacements no longer work with assets. Here is the code snippet that I am using: "fileReplacements": [ { "replace": "src/assets/scss/x.scss", ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...

The browser is preventing a cross origin request in Fetch

Currently, I am utilizing node, express, and react to build a sign-in portal. In the frontend, I have created app.js and signin.js files. The partial code snippet in the signin.js file looks like this: onSubmitSignIn = () => { fetch("http://localhost:3 ...

Position div elements randomly on the webpage when it first loads

I am trying to achieve a set of divs that will appear randomly on the page when it loads. Currently, I have the divs moving around the viewport in a random manner, but they all seem to load in the top left corner. This is the method I am currently using: ...

trim() function acting strangely

There seems to be an unexpected occurrence with the trim() function, as it is removing the á character. https://i.stack.imgur.com/whZBN.png This particular code snippet is typically used in various JavaScript projects without any issues. However, a clie ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Place the text within the contenteditable body of a frame at the specific caret position

Within my iframe object, there is a contenteditable body. I am trying to paste text or HTML elements at the caret position. However, when I attempted this code snippet, I encountered an error message saying Cannot read property 'createRange' of u ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

Improving mongo information using angularjs

Have an Angular and MongoDB application. This is a part of my API where I have POST and PUT requests. The POST request works fine, but when I send a PUT request, I get an error "Cannot set property 'typelocal' of undefined". However, the PUT requ ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Options for Angular's routerLinkActiveDirective

I have a link that looks like this <li routerLinkActive="active" class="nav-item"> <a [routerLink]="['contracts']" [queryParams]="{ activeOnly: false }" class="nav-link">Contracts</a> </li> As you can see, in the param ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

Tips for animating a nested array using jQuery

I have a border that is 9x9 with lines, columns, and squares, similar to a Sudoku border. I want to animate it, but I encountered some issues when trying to run multiple animations simultaneously. To solve this problem, I decided to animate one array of el ...

Error encountered during Heroku deployment: "sh: 1: tailwind: not found"

package.json: "devDependencies": { "tailwindcss": "^0.7.4" }, "scripts": { "tailwind:css": "tailwind build src/css/tailwind.src.css -c tailwind.js -o src/css/tailwind.css", "start": "npm run tailwind:css && react-scripts start", ...

Utilizing JavaScript to trigger an alert message upon selecting various options and blocking the onclick event

Setting up a simpleCart(js) with selectable options presents a challenge. The task at hand is to display an alert if not all drop-downs meet specific requirements and to prevent the "Add to cart" button from adding items to the cart when these conditions a ...

What is the method for closing an <iframe> element directly?

A web page called room.html contains a table with an onclick function named place(): function place() var x = document.createElement("IFRAME"); x.setAttribute("src", "loading.html"); document.body.appendChild(x); } What is ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...