简体   繁体   中英

Conditional required validation in angular forms

If both fields dont 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 its like if i am the user and there are two fields which is firstname nad lastname. If i input data on firstname but lastname is empty then set the lastname as required (vice versa). Any idea? thanks

#html code

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

#code

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

Subscribe for the form control value changes and update the value and validity based on the condition.

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

Working Code

https://stackblitz.com/edit/angular-wfab5s?file=src%2Fapp%2Fapp.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM