Home > OS >  Angular Form Validations Required field optional field
Angular Form Validations Required field optional field

Time:11-22

So my question is. I have a very huge form to fill in 200 input fields and I have one field required (the title) but I also wanna check that they fill in at least one other field. doesn't matter which one. but once that requirement is met they can submit the form.

CodePudding user response:

This is easy, see Stackblitz example. You only need to set a Validator to one field and then check onSubmit all other fields values:

  onSubmit(): void {
    let anyOtherControlIsFilled = false;

    Object.keys(this.form.controls).forEach((key) => {
      if (!this.form.controls[key].validator) {
        if (
          this.form.controls[key].value !== null &&
          this.form.controls[key].value !== ''
        ) {
          console.log('Passt');
          anyOtherControlIsFilled = true;
        }
      }
    });

    if (this.form.valid && anyOtherControlIsFilled) {
      this.submitted = true;
      alert('All ok');
    } else {
      this.submitted = true;
      alert('Error');
      return;
    }

    console.log(JSON.stringify(this.form.value, null, 2));
  }

Greetings, Flo

CodePudding user response:

Add validator to FormGroup to check all inputs.

new FormGroup(
  {
    requiredControl: new FormControl(initialValue, [Validators.required]),
    control1: new FormControl(...),
    ...
    control200: new FormControl(...)
  },
  [someValueValidator()]
)

private someValueValidator() {
  return (controls: AbstractControl) => {
   // check if any non-required control is set then return null, 
   // otherwise return ValidationError
  }
}
  • Related