Using Angular to Apply a Custom Validation Condition on a FormGroup Nested Within Another FormGroup

I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the code snippet for my form and validation function:

  readonly closeFormGroup: FormGroup;


  constructor(
    formBuilder: FormBuilder,
  ) {
    this.closeFormGroup = formBuilder.group({
      notes: [null],
      reason: [1, Validators.required],
      checkBoxGroup: new FormGroup({
        checkBox1: new FormControl(false),
        checkBox2: new FormControl(false),
        checkBox3: new FormControl(false),
        checkBox4: new FormControl(false),
        checkBox5: new FormControl(false),
      } ,this.requireCheckboxesValidator())
    });
  }
  public requireCheckboxesValidator(): ValidatorFn {
    return function validate(formGroup: FormGroup) {
      let checked = 0;
      console.log(formGroup);
      Object.keys(formGroup.controls).forEach(key => {
         const control = formGroup.controls[key];

         if (control.value === true) {
           checked++;
         }
       });

      if (checked < 1) {
        return {
          requireCheckboxesToBeChecked: true,
        };
      }

      return null;
    };
  }

Answer №1

If you're looking for a different strategy, consider subscribing to the valueChanges of your dropdown field. Then, if the selected value meets your criteria, use addValidator to apply a specific validator to your checkboxes form control. I appreciate your idea of incorporating a custom validator, which is indeed a more effective approach. Essentially, you want to apply the validator to the checkboxes only when a particular value is chosen from the dropdown. To achieve this, adjust your logic as follows:

Object.keys(formGroup.controls).forEach(key => {
   const control = formGroup.controls[key];

   if (control.value === true) {
     checked++;
   }
  let dropdownValue = undefined;
  if (key === 'dropdownFormControlKey') {
      dropdownValue = control.value;
  }
 });

if (checked < 1) { 
  return {
    requireCheckboxesToBeChecked: true,
  };
}

return null;
};

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

Easily automate button clicks on a new tab website

Seeking assistance below, following codes are sourced from "example.com" as assumed: <a href="http://www.example.org" target="vo1" onclick="gp(1)" rel="nofollow">Click Me</a> Upon clicking on ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

JavaScript string representing the actual value of a string

In order to reliably extract string literals from a JavaScript string, I need to create a function, let's name it f. Here are some examples: f('hello world') //-> 'hello world' (or "hello world") f('hello "world"') / ...

Invoke a Google Apps Script through AJAX that necessitates authentication

I am looking to access a Google Apps Script via AJAX that requires user authorization to send an email from their Gmail account. The challenge lies in the fact that I need to send the email from within the Google Apps Script. The call originates from my w ...

Using React, retrieving the value of a checked radio button from the state

My issue involves a list of radio buttons generated from a map loop containing numbers like 1, 2, and 3. When I select a radio button, it should set a state: <ul className="flex gap-6 justify-center"> {maxPaxArr.map((keypax) => ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

Customizing table headers in Yajra Laravel Datatables

I am encountering an issue with category sorting on my list of products. When I click on category sorting, it only shows the same category and product name repeatedly. All other sorting functions are working correctly, except for category sorting. I have ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

How to automatically scroll to the most recently added element in an *ngFor loop using Angular 2

In my web page, I have a dynamic list rendered using an ngFor loop. Users can add or remove elements from this list by clicking on a button. What I want to achieve is to automatically scroll the browser view to the latest element added when a user clicks o ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

Looking to update the state of a nested object with useReducer?

I am currently developing a Next.js application using Typescript and I need to make changes to a nested object state. Here is the structure of the state: const initialState ={ userInfo: string | null, isLoading: boolean, cursorState: boolean, compa ...

AngularJS and IE8 don't play nice when it comes to handling dynamic content

Below is the code snippet I am working with: <blockquote class='mt20'> <p><span>&ldquo;</span><span>{{iq.quote}}</span><span>&rdquo;</span></p> <footer><cite class="d ...

Implementing useState to toggle the checked value of a checkbox in React

When passing a list of checkbox fields with attributes to my component, I want to update the checked attribute based on user selection. However, all I have managed to do so far is double the check value in an array. How can I modify this specific key with ...

Using Node and Express to handle form submissions, we can create a POST request that sends data to the server

Despite my ongoing learning journey, I am feeling a bit frustrated as I struggle to find a solution for this particular issue using ES6 Javascript. Currently, I have a straightforward todo-list web-app where everything is managed and displayed through the ...

Comparing non-blocking setTimeout in JavaScript versus sleep in Ruby

One interesting aspect of JavaScript is that, being event-driven in nature, the setTimeout function does not block. Consider the following example: setTimeout(function(){ console.log('sleeping'); }, 10); console.log('prints first!!') ...

Want to learn how to integrate React-pdf (@react-pdf/renderer) with TypeScript on NodeJS and Express JS?

I am encountering difficulties running React-Pdf (@react-pdf/renderer) with TypeScript on an Express JS server. I have attempted to use babel but encountered errors that I cannot resolve. build error error error You can find the Github repository for t ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

Enhancing user experience with dynamic search results: JQuery AutoComplete powered by XML

As a newcomer to AJAX, JavaScript, and the web, I'm struggling with understanding this concept. When using JQuery's autocomplete feature with a small flat file of limited items (suggestions.xml), everything works perfectly. However, when switchin ...