【问题标题】:How to use required validation on <input type="file"> in angular 4如何在角度 4 中对 <input type="file"> 使用所需的验证
【发布时间】:2017-07-05 23:04:27
【问题描述】:

文本输入工作正常。我对文件使用了相同的方法,但它不起作用。

<input type="text" name="title" #title="ngModel" ngModel required class="form-control" placeholder="Title Here">
<div *ngIf="title.errors && (title.dirty || title.touched)">
    <span class="help-block error" [hidden]="!title.errors.required"> Title 
      is Required 
    </span>
</div>
<input type="file" #image="ngModel" (change)="fileEvent($event)" 
name="image" ngModel>

【问题讨论】:

  • 查看我的回答 here 以获得完整的工作示例 + 解释

标签: javascript angular validation


【解决方案1】:

如果您只想显示/隐藏错误消息取决于所选文件

@Component({
  selector: 'my-app',
  template: `
    <div>
       <input type="file" (change)="onChange($event)" name="image">
      <div *ngIf="!fileSelected">
      <span class="help-block error" [hidden]="!fileSelected"> 
        File is Required 
      </span>
     </div>
    </div>
  `,
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
    this.fileSelected = files.length>0;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多