Require one from two fields using Angular 2

后端 未结 4 1766
感情败类
感情败类 2020-12-29 09:02

I\'m trying to create a contact form. The form looks like this:

4条回答
  •  不知归路
    2020-12-29 10:06

    I created a custom validator directive:

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

    To use it, you just do this:

    this.form = this.formBuilder.group({
                name: ['', Validators.required],
                email:[''],
                telefone:[''],
                message:['', Validators.required],
            }, { validator: atLeastOne(Validators.required, ['email','telefone']) });
    

    So email or telefone would be required here. If you leave it empty then any control with a value is fine and you can use it with any type of validator, not just Validators.required.

    This is reusable in any form.

提交回复
热议问题