使用Angular 4中的Custom Validator进行反应表单验证

时间:2018-04-10 09:50:58

标签: angular angular-reactive-forms angular2-form-validation

我有一个包含两个字段的表单...一个是一组3个复选框(其中一个必须选中),另一个是输入类型作为文件。(必须选中)。 我正在为它们使用反应式表单自定义验证器,并且只有在为表单提供poper值之后,我才能启用提交按钮。但验证器似乎没有起作用。

HTML页面:

<input type="file"  id="selectFile" #selectFile accept=".zip" formControlName ="fileUpload" name="file" class="form-control"  class="btn" value="file" required />
<span *ngFor="let tool of toolTypeList">
  <label class="checkbox-inline col-md-2 " style = "text-align: left;padding-left:35px"> 
    <input type="checkbox"  formControlName ="selectTool"
      name="{{tool.toolType}}" 
      value="{{tool.toolType}}"
      (change)="change($event, tool)">
      {{tool.toolType}}
  </label>
</span>

组件:

this.rForm = fb.group({
  'selectTool': new FormControl('', [
    Validators.required,
    this.validateTools
  ]),
  ' fileUpload': new FormControl('', [
    Validators.required,
    this.noFilePresent
  ]),
});

校验:

noFilePresent(): Boolean {
  if (this.fileuploaded.size <= 0) {
    return true;
  }
  return false;
}

validateTools(c: AbstractControl) {
  console.log('here in custom validator : ' + c.value);
  let response: any = null;
  if (c.value == null) {
    response = this.selectedTools.length > 0 ? null : {
      validateTools: {
        valid: false
      }
    };
  }

我假设对于fileUpload字段,创建的验证器在其结构中是错误的,因为没有formcontrol对象作为参数传递。但是大概是复选框(selectTool)验证器的正确结构,它不起作用。请帮我找出错误。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我创建了这样的自定义验证器。如果你只需要他们就可以在你的班级,就像你一样。

private noFilePresent(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        if(control.value == null || control.value.length == 0) {
            return {'uploadInvalid': {value: control.value}};
        }
        return null;
    }
}

我认为这里的control.value值可以是任何值。然后,您可以使用getter检查是否存在错误

 get upload() { return this.rForm.get('fileUpload'); }

和其他地方

 if(this.upload.errors.uploadInvalid) {
     // do stuff or return error message or something
 }
相关问题