1

I've made a custom form control with multiple input fields. I want to make my custom control validate in a way that if I assign Validators.required to it, it would only be valid if all the inputs inside it are filled.

Kind of higher level "required" on the control as a whole.

1 Answer 1

2

create your own custom validator, put it into 2 param when you create formGroup. in custom validator, you could loop through all controls then get value -> validate value as you want.

Online demo: https://plnkr.co/edit/pcXsxP?p=preview

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms'

import { CustomValidators } from './custom.validators';

@Component({
  selector: 'app-root',
  template: `
    <form (ngSubmit)="onSubmit()" novalidate [formGroup]="fg">
      <div><input type="text" formControlName="input1"></div>
      <div><input type="text" formControlName="input2"></div>
      <div><input type="text" formControlName="input3"></div>
      <div><input type="text" formControlName="input4"></div>
      <div><input type="text" formControlName="input5"></div>
      <button type="submit">Submit</button>
      <p>Status {{ fg.valid }}</p>
    </form>
  `
})
export class AppComponent implements OnInit {
  fg: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {

    this.fg = this.fb.group({
      input1: '',
      input2: '',
      input3: '',
      input4: '',
      input5: '',
    }, {
      validator: CustomValidators.multipleInputRequired
    });

  }

  onSubmit() {
    console.log(this.fg);
  }
}

custom.validator.ts

import { FormGroup } from '@angular/forms';

export class CustomValidators {
  static multipleInputRequired(fg: FormGroup) {
    let controls = fg.controls;
    let valid = true;
    if (controls) {
      for (let c in controls) {
        if (controls[c].value.trim() == '') {
          valid = false;
        }
      }
    }
    return valid ? null : {
      multipleInputRequired: true
    };
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The answer would be a lot better with an example validator, and usage scenario(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.