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

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

KnockoutJS - Struggling to bind model from simple JSON array

I've been working on an application that relies on a static JSON array, without the support of a backend service. I've been attempting to bind this JSON array to the page using KnockoutJS. Although I can successfully load the JSON array and creat ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

How can you modify Jquery show_hide so that the page automatically scrolls to the bottom of the concealed field when the button is clicked?

On my website, there is a button that reveals a map when clicked. The button is visible when the page loads, but once clicked, the map slides open and goes out of sight since the page loads at the top as usual. My goal is to have the page automatically scr ...

Navigating through documents in Jhipster (Angular + Springboot)

After successfully developing a controller and service in the backend using Spring, I have managed to implement file upload functionality on the server. To determine the upload location, I utilized System.getProperty("user.dir") to retrieve the current pr ...

Difficulty accessing files with Angular deployment in Nginx through Docker

Recently, I delved into the world of Docker and Nginx in an attempt to deploy my angular application. Unfortunately, I encountered a perplexing issue. Upon executing the command: npm run build, I noticed that my index.html contained script references as f ...

Can files in a directory be listed using JavaScript without the need for HTML tags?

Currently, I am exploring ways to automate an Angular application using Protractor. During this process, I encountered a situation where I needed to retrieve a list of all the files within a specific folder. In Java, I am aware that we can accomplish this ...

Utilizing traditional JavaScript variables within Express.js or Node.js: A comprehensive guide

How can I successfully export variables from regular JavaScript to be used in ExpressJS? I attempted to use 'exports' but it didn't yield the desired results. For instance, in a regular JS file: var search = 'hello'; exports = s ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

What are the steps to employ a query string to display a specific image?

If I understand correctly, I can utilize a query string and parse it to display certain information. How would I apply that concept to load a specific image? https://codepen.io/anon/pen/qYXexG <div id="gallery"> <div id="panel"> <img ...

Is it possible to locate an element using regex in Python while using Selenium?

Is it possible to interact with a dynamically generated dropdown list using Selenium if I only know the phrase present in its id or class name? Can Selenium locate an element using regex and click on it accordingly? ...

When using res.render to pass data to an EJS file and accessing it in plain JavaScript

I'm currently working on an Express GET function where I am sending data to an EJS file using the res.render() function. My question is, how can I access this data in plain JavaScript within the same EJS file? Here is my GET Function: router.get(&a ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

What is the best way to pinpoint a specific Highcharts path element?

I am currently working on drawing paths over a graph, and I am looking to dynamically change their color upon hovering over another element on the page - specifically, a list of data points displayed in a div located on the right side of my webpage. Below ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

Using Angular's FormControl with a Pipe

Trying to manipulate the value of an <input> using a pipe and display the modified value in a <paragraph> has proven to be quite challenging. Despite various attempts and thorough research, I have not been able to achieve the desired functional ...