Angular 7-仅在选中复选框时验证输入字段

时间:2019-02-21 16:18:11

标签: angular angular-validation

我使用的是角度7,并且我有一个带有两个输入字段的表单,尽管始终需要第一个输入字段,但只有在选中复选框的情况下才需要第二个输入字段。

我正在尝试使用带有自定义验证程序的FormGroup:

If NOT exist c:\1\1.txt EXIT

Echo EXIST

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox [(ngModel)]=" checked" [ngModelOptions]="{standalone:true}">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>

问题在于,仅当更新两个输入字段中的文本时才执行验证,而如果我选中/取消选中复选框,则状态不会更改,并且要强制验证,我必须更改第二个文本框。

Here,您可以在stackblitz上看到一个示例:如果选中此复选框,状态不会改变。

当复选框状态更改时,如何强制验证?

3 个答案:

答案 0 :(得分:1)

您需要使用跨域验证。在表单组中添加复选框

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox formControlName="checked">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>


ngOnInit() {
  this.exampleForm = new FormGroup({
    'second': new FormControl(''),
    'checked': new FormControl(false),
    'first': new FormControl('example')
  }, [this.validateIfChecked()]);
}


validateIfChecked(): ValidatorFn {
  return (form: FormGroup): ValidationErrors | null => {
    const checked = form.get('checked');
    const second= form.get('second');
    if (checked && !second) {
      return {
        'err': true
      };
    }
    return null;
  }
}

在这种情况下,如果'checked'为true,则需要'second'

如有疑问,https://angular.io/guide/form-validation#cross-field-validation

答案 1 :(得分:0)

您可以根据所单击的复选框向表单控件动态添加所需的验证。

模板:

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox [(ngModel)]="checked" [ngModelOptions]="{standalone:true}" (click)="checkstate()">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>

组件:

checkstate(){
  this.checked = !this.checked;
  if(this.checked){
     this.exampleForm.get('second').setValidators(Validators.required);
  }else{
     this.exampleForm.get('second').clearValidators();
  }
  this.exampleForm.get('second').updateValueAndValidity();
}

答案 2 :(得分:0)

如果您实际上不想在表单中包含复选框值,则可以制作一个单独的表单控件,该控件不包含在表单中。根据复选框的值,您可以清除验证器或添加所需的验证器:

checked = new FormControl(false);

// ...

this.checked.valueChanges.subscribe((bool: boolean) => {
  bool ? this.exampleForm.get('second').setValidators(Validators.required) : 
         this.exampleForm.get('second').clearValidators();
  this.exampleForm.get('second').updateValueAndValidity();
});

以及相关模板:

<mat-checkbox [formControl]="checked">Make second input field required</mat-checkbox>

您分叉的 StackBlitz

相关问题