How to override "required" validator in custom control Angular2

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.

Upvotes: 1

Views: 4002

Answers (1)

Tiep Phan
Tiep Phan

Reputation: 12596

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
    };
  }
}

Upvotes: 2

Related Questions