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

How can I extract the text enclosed in <li> tags using JavaScript?

Can someone help me with retrieving the text content of li tags? I managed to get a list of lis, but I'm having trouble assigning the text content to my country object. Snippet var lis = document.getElementById("navbar").getElementsByTagName("l ...

Sorting through items within a container object

I am currently working with an object named 'docs' that contains multiple objects within it. I am attempting to determine the count of entries that have specific values for both 'exopp_rooms_id_c' and 'is_active'. While this m ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

Building a MEAN stack application using Angular 5 and implementing passportJS for authentication

What's the process for implementing authentication in a MEAN stack using Angular 5, Node.js, and Passport.js? ...

Issue with submitting input fields that were dynamically added using jquery

I created a table where clicking on a td converts it into an input field with both name and value. The input fields are successfully generated, but they do not get submitted along with the form. In my HTML/PHP : <tr> <f ...

Authenticate users by accessing their login information stored in a MongoDB database using Node.js and Express

I have been experimenting with various techniques, and incorporating Passport middleware has brought me the closest to achieving this task. I suspect there might be a final step missing for everything to function correctly, as I am not encountering any err ...

The element is implicitly imparted with an 'any' type due to the incapability of utilizing an expression of type 'number' to index the type '{}'. This error occurs in the context of VUEJS

I have encountered an issue that I have been struggling to resolve despite trying numerous solutions. The problem arises while working on a project using Vue. Here is how I have structured my data: data(){ return{ nodes: {}, edges:{}, ...

Angular request: HTTP request<any> is not generic

Struggling with creating an error interceptor service in Angular. Having trouble instantiating a HttpRequest. New to Angular and Web App development. Here is my code snippet: import { Injectable } from '@angular/core'; import { HttpInterceptor ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

Tips for effectively utilizing 'ngModel' alongside a form control name

When a user enters or inserts a value into one textarea, I want it to automatically update the other textarea field as well. I thought about using the change function to achieve this, but when I tried to use ng-model with the control name, I encountered a ...

Setting up Mongoose with Admin JS in NestJS: A Step-By-Step Guide

After successfully configuring adminJS in my Nest JS application, it now runs smoothly on localhost:5000/admin. @Module({ imports: [ import('@adminjs/nestjs').then(({ AdminModule }) => AdminModule.createAdminAsync({ ...

Avoiding hydration errors when using localStorage with Next.js

Want to save a token and access it using local storage The code snippet I am using is: if (typeof window !== 'undefined') { localStorage.setItem(key, value) } If I remove the window type check, I encounter this error: localStorage is not ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

Errors detected while attempting to install dependencies using pnpm: modules unspecified

I recently decided to experiment with using pnpm instead of npm for my new projects, but I've encountered an issue. Let's take my nuxt project as an example. First, I set up my project using the command: pnpx nuxi init my-project Then, I insta ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

When trying to access the same path, useEffect does not trigger

I integrated the API to execute when the screen is loaded using useEffect in Next.js v10. The code implementation is straightforward: ... const fetchAPI = async () => { try { await axios.get({ .... }) } catch (e) { console.error(e) } } R ...

What steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

Displaying a default input placeholder in Kendo UI Datepicker for Angular 2

I've recently implemented the [Datepicker feature from Telerik Kendo UI][1] While the datepicker functions perfectly, I have encountered a single issue where it displays undefined when the date value is not defined: [![enter image description here][ ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

Enhancing JavaScript Objects with New Key/Value Pairs

I'm trying to wrap my head around the code structure of a solution I stumbled upon. The issue at hand: Create a function that takes in a string with only lowercase letters as a parameter, and returns an object with each letter and the number of times ...