How to implement Conditional required validation in angular forms?

Viewed 326

If both fields don't have inputs then both can be optional. If firstname has input then set lastname as required. If lastname has input but firstname has no input then set firstname as required.

Set other field as required if one field has value and the other has not. Thank you.

So it's like if i am the user and there are two fields which is firstname and lastname. If i input data on firstname but lastname is empty then set the lastname as required (vice versa). Any idea ? thanks

HTML

<div fxLayout="row" fxLayoutGap="24px" formGroupName="person">
  <div fxFlex fxLayout="row">
    <mat-form-field appearance="outline" class="pr-4" fxFlex>
      <mat-label>Firsname</mat-label>
      <input matInput #firstname formControlName="firstname" trim  required/>
      <button type="button" mat-button   *ngIf="firstname.value"  matSuffix mat-icon-button aria-label="Clear"
      (click)="clearFieldFirstname()">
      <mat-icon>close</mat-icon>
    </button>
    </mat-form-field>
  </div>
  <div fxFlex fxLayout="row">
    <mat-form-field appearance="outline" class="pr-4" fxFlex>
      <mat-label>Lastname</mat-label>
      <input matInput #lastname formControlName="lastname" trim required/>
      <button type="button" mat-button   *ngIf="lastname.value"  matSuffix mat-icon-button aria-label="Clear"
      (click)="clearFieldLastname()">
      <mat-icon>close</mat-icon>
    </button>
    </mat-form-field>
  </div>
</div>

TS CODE

const personGroup = this.formBuilder.group({
  firstName: [person.firstName, Validators.required],
  lastName: [person.lastName, Validators.required],
});

const formGroup = this.formBuilder.group({
  person: personGroup,
});

this.person.get("firstname").valueChanges.subscribe(value => {
  const lastName = this.person.get("lastname");
  lastName.clearValidators();
  if (value && !lastName.value) {
    lastName.setValidators(Validators.required);
  }
  lastName.updateValueAndValidity({
    emitEvent: false
  });
});

this.person.get("lastname").valueChanges.subscribe(value => {
  const firstName = this.person.get("firstname");
  if (value && !firstName.value) {
    firstName.setValidators(Validators.required);
  } else {
    firstName.clearValidators();
  }
  firstName.updateValueAndValidity({
    emitEvent: false
  });
});
1 Answers
const personGroup = this.formBuilder.group({
  firstName: [
    person.firstName,
    (control: AbstractControl): ValidationErrors | null => {
      // do your validation logic here:
      if (this.formGroup?.get('lastName').value) {
        if (!control.value) {
          return {required: true};
        }
      }
      // all is fine:
      return null;
    }
  ],
  lastName: [
    person.lastName,
    (control: AbstractControl): ValidationErrors | null => {
      if (this.formGroup?.get('firstName').value) {
        if (!control.value) {
          return {required: true};
        }
      }
      return null;
    }
  ],
});
Related