Angular form validation: compare two fields in different form groups

人盡茶涼 提交于 2021-02-19 02:24:24

问题


I'm sorry if it's a duplicate of someone question. I didn't find a solution for my problem.

Can anybody explain or give an example how to compare two fields in one form but in different form groups?

Here is code snippet to see how my form and validator are look like:

private createForm() {

    const testGroups = {
        groupOne: this.fb.group({
            fieldOne: this.fb.control(null)
        }),
        groupsTwo: this.fb.group({
            fieldTwo: this.fb.control(null, [this.matchValidator])
        })
    };

    this.testForm = this.fb.group(testGroups);
}

 matchValidator(from: FormControl): ValidatorFn {
    return (to: AbstractControl): { [key: string]: any } => {
        return from.value && to.value && from.value === to.value
            ? { fieldMatch: true }
            : null;
    };
}

回答1:


matchValidator will be called by Angular and not by you. So it won't have the access to the Component's this.

So you will have to bind to it.

You can use the get method on a FormGroup to get the group1's field's value: (<FormGroup>this.mainForm.get('group1')).get('field').value

Give this a try:

Component Class:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  mainForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.mainForm = this.fb.group({
      group1: this.fb.group({
        field: []
      }),
      group2: this.fb.group({
        field: [null, [this.matchValidator.bind(this)]]
      })
    });

  }

  matchValidator(control: AbstractControl): { [key: string]: boolean } | null {
    const fromValue = control.value;
    if(this.mainForm) {
      const toValue = (<FormGroup>this.mainForm.get('group1')).get('field').value;
      if (fromValue && toValue && fromValue === toValue) {
        console.log('Control: ', control);
        return { 'fieldMatch' : true };
      }
      console.log('Control: ', control);
      return null;
    }
  }

  get group2Field() {
    return (<FormGroup>this.mainForm.get('group2')).get('field');
  }
}

Template:

<form [formGroup]="mainForm">
  <div formGroupName="group1">
    <label for="">Group 1 Field</label>
    <input type="text" formControlName="field">
  </div>
  <hr>
  <div formGroupName="group2">
    <label for="">Group 2 Field</label>
    <input type="text" formControlName="field">
    <p *ngIf="group2Field?.errors?.fieldMatch">These fields match</p>
  </div>
</form>

Here's a Sample StackBlitz for your ref.



来源:https://stackoverflow.com/questions/53426241/angular-form-validation-compare-two-fields-in-different-form-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!