角度6:自定义验证程序,以确保用户至少选择了一个字段

时间:2018-09-25 15:09:15

标签: angular angular6 angular-reactive-forms angular-validation

确保用户至少选择一个选择标准的功能

identityRevealedValidator = (validator: ValidatorFn) => (
    group: FormGroup,
  ): ValidationErrors | null => {
    const identityRevealed = group && group.controls && Object.keys(group.controls)
      .some(k => !validator(group.controls[k]));

    return identityRevealed ? null : {
      identityRevealedValidator: true,
    };
  };

该函数的实例:

{ updateOn: 'submit', validator: this.identityRevealedValidator }

表格内部的用法:

<form [formGroup]="form"> 
          <div class="form-row">
            <div class="col-md-12 text-right mt-3">
              <button type="submit" class="btn btn-primary" [disabled]="!form.valid">Search</button>
              <div *ngIf="form.errors?.identityRevealed && (form.touched || form.dirty)" class="cross-validation-error-message alert alert-danger">
                  PLease select one Field
              </div>
            </div>
          </div>
        </form>

0 个答案:

没有答案