如果文件格式不是doc或docx,则在输入类型文件Form Control上显示验证错误消息

时间:2019-07-06 01:25:52

标签: html angular typescript

如果用户提交的文件不是docdocx类型的文件,我希望显示警报。我为此编写了一个验证器,如果验证器未通过,希望警报显示(文件类型不可接受)。

打字稿:

this.resume_form = this.fb.group({
  name: ['', [Validators.required, this.nameValidator]],
  email: ['', [Validators.required, Validators.email, Validators.pattern(emailRegExp)]],
  resume: ['', [Validators.required, this.fileValidator]],
  cv: []
})

fileValidator(): ValidatorFn {
  return (control: AbstractControl): {
    [key: string]: boolean
  } | null => {
    let filename = control.value;
    filename = filename.substring(filename.lastIndexOf(".") + 1);
    for (let i = 0; i < this.validFileTypes.length; i++) {
      console.log(filename + " " + " " + this.validFileTypes[i]);
      if (filename === this.validFileTypes[i]) {
        return null;

      }
    }
  }
}

HTML:

<div class="form-group">
  <label for="resume"> Resume*</label>
  <input type="file" id="resume" class="form-control-file" formControlName="resume" required>
  <div class="alert alert-warning" *ngIf="resume_form.controls.resume.errors?.required && resume_form.controls.resume.touched required">Please Upload File </div>
  <div class="alert alert-warning" *ngIf="resume_form.controls.resume.errors?.resume">Unacceptable File Type </div>
</div>

1 个答案:

答案 0 :(得分:0)

据我所知,您必须处理change上的<input type="file" />事件

在这里,一旦获得文件列表,就必须检查有效的文件名,然后在setErrors上相应地检查FormControl

因此,您可以在setErrors(...)上使用AbstractFormControl API。

尝试一下:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators, ValidatorFn, AbstractControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  resume_form: FormGroup;
  validFileTypes = ['doc', 'docx'];

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.resume_form = this.fb.group({
      resume: ['', [Validators.required]],
    })
  }

  onChange($event) {
    const fileName = $event.target.files[0].name;
    const fileEntension = fileName.split('.').pop();
    if (this.validFileTypes.indexOf(fileEntension) > -1) {
      this.resume_form.controls['resume'].setErrors(null);
    } else {
      this.resume_form.controls['resume'].setErrors({ resume: true });
    }
  }
}

在模板中:

<div 
  class="form-group"
  [formGroup]="resume_form">
    <label for="resume">Resume*</label>
  <input 
    type="file" 
    id="resume" 
    class="form-control-file" 
    formControlName="resume"
    (change)="onChange($event)"
    required>
  <div 
    class="alert alert-warning" 
    *ngIf="resume_form.controls.resume.errors?.required && resume_form.controls.resume.touched required">
    Please Upload File
  </div>
  <div 
    class="alert alert-warning" 
    *ngIf="resume_form.controls.resume.errors?.resume">
    Unacceptable File Type
  </div>
</div>

  

这是您推荐的Working Sample StackBlitz