Angular2 FormBuilder Validatiors: require at least one field in a group to be filled

后端 未结 2 525
孤街浪徒
孤街浪徒 2020-12-13 19:29

I have a form where I\'m collecting phone numbers (mobile, personal, other). I need to have at least input populated. I\'m trying to use Angular2 FormBuilder.

Afte

相关标签:
2条回答
  • 2020-12-13 20:06

    I use an atLeastOne function that creates a custom validator based on any existing validator:

    import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
    
    export const atLeastOne = (validator: ValidatorFn) => (
      group: FormGroup,
    ): ValidationErrors | null => {
      const hasAtLeastOne =
        group &&
        group.controls &&
        Object.keys(group.controls).some(k => !validator(group.controls[k]));
    
      return hasAtLeastOne ? null : { atLeastOne: true };
    };
    

    The beauty is that you can use any validator with it and not just Validators.required.

    In OP's case, it'll be used like this:

    {
      phone: this._fb.group({
        other: [''],
        personal: [''],
        mobile: [''],
      }, { validator: atLeastOne(Validators.required) })
    }
    
    0 讨论(0)
  • 2020-12-13 20:09

    This is a generic code that you can use with every FormGroup:

    export function AtLeastOneFieldValidator(group: FormGroup): {[key: string]: any} {
      let isAtLeastOne = false;
      if (group && group.controls) {
        for (const control in group.controls) {
          if (group.controls.hasOwnProperty(control) && group.controls[control].valid && group.controls[control].value) {
            isAtLeastOne = true;
            break;
          }
        }
      }
      return isAtLeastOne ? null : { 'required': true };
    }
    

    And the usage:

    @Component({
      selector: 'app-customers',
      templateUrl: './customers.component.html',
      styleUrls: ['./customers.component.scss']
    })
    export class CustomersComponent implements OnInit {
    
      public searchCustomerForm: FormGroup;
    
      constructor() { }
    
      ngOnInit() {
        this.searchCustomerForm = new FormGroup({
          customerID: new FormControl(''),
          customerEmail: new FormControl(''),
          customerFirstName: new FormControl(''),
          customerLastName: new FormControl('')
        }, AtLeastOneFieldValidator);
      }
    }
    
    0 讨论(0)
提交回复
热议问题