POV
POV

Reputation: 12015

How to set form valid by condition?

I have validation form:

public initStep6() {
    return this.fb.group({
      'name': ['', [Validators.required]]
    });
  }

Also I have checkbox on the page, if it is checked form should be valid even if filed name is empty.

How to make form valid without filling fields?

Upvotes: 0

Views: 1077

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38807

If I'm understanding correctly, you want the form to be valid if either name has a value OR the checkbox (which you didn't include in the form group) is checked. You can use a custom ValidatorFn function on the FormGroup to check for values across multiple fields. This is effectively from the Cross Field Validation example in the form validation documentation. It would look something like this:

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

const myValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => {
  // get controls
  const name = formGroup.get('name');
  const myCheckbox = formGroup.get('myCheckbox');

  // validate however needed, e.g. length/pattern/etc
  const isNameValid: boolean = name && name.value && name.value.length > 0;
  const isCheckboxValid: boolean = myCheckbox && myCheckbox.value && myCheckbox.value === true;

  // return null if valid otherwise return object with custom key/value
  return (isNameValid || isCheckboxValid) ? null : { 'formValid': false };
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  myFormGroup: FormGroup;
  name = 'Angular';

  constructor(private fb: FormBuilder) { }

  onSubmit() {
    console.log('submitted!');
  }

  ngOnInit() {
    // key thing here is passing the ValidatorFn as the 2nd argument to expose the FormGroup in the ValidatorFn rather than a FormControl
    this.myFormGroup = new FormGroup({
      'name': new FormControl(),
      'myCheckbox': new FormControl()
    }, { validators: myValidator });
  }
}

Template:

<form [formGroup]="myFormGroup" *ngIf="myFormGroup" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" formControlName="name" />
  </div>
  <div>
    <label for="myCheckbox">My Checkbox:</label>
    <input type="checkbox" name="myCheckbox" id="myCheckbox" formControlName="myCheckbox" />
  </div>
  <div>
    <button type="submit" [disabled]="!myFormGroup.valid">Submit!</button>
  </div>

  <div *ngIf="myFormGroup.errors">
    {{myFormGroup.errors | json}}
  </div>
</form>

I've created a StackBlitz to demonstrate the functionality including disabling submit if form is invalid.

Hopefully that helps! If this isn't what you are looking for you really need to add more information to your question.

Upvotes: 1

Related Questions