0

In Angular 2 how to validate if a file is really an image?

isImage(file: File): boolean {
    return /^image\//.test(file.type);
}

In the above function after an upload, simply change the .txt to .png file extension it returns true eg: text.txt to text.png

4 Answers 4

3

HTML <input> has an attribute which you can use.

<input accept=".png, .text" />
Sign up to request clarification or add additional context in comments.

Comments

2

You can check easily with file type. If example it it's video type will be "video/format" or if it's image it will be "image/format". you can use this.

event.target.files[0].type.includes('image')

Comments

1

The following is not specifically about Angular but it does answer the question of doing client side file type validation in javascript. It should be easy enough to adapt the solution for your needs: How to check file MIME type with javascript before upload?

Comments

0

Here is a custom directive for that. You can use it for other file types too. Just add/remove your required extensions in RegExp

import { FormControl, NG_VALIDATORS, Validator } from '@angular/forms';
import { Directive } from '@angular/core';

@Directive({
  selector: '[FileTypeValidator]',
  providers: [
    {
      provide: NG_VALIDATORS, useExisting: FileTypeValidator, multi: true
    }
  ]
})
export class FileTypeValidator implements Validator {

  static validate(c: FormControl): { [key: string]: any } {
    if (c.value) {
      if (c.value[0]) {
        return FileTypeValidator.checkExtension(c);
      };
    }
  }

  private static checkExtension(c: FormControl) {
    let valToLower = c.value[0].name.toLowerCase();
    let regex = new RegExp("(.*?)\.(jpg|png|jpeg)$"); //add or remove required extensions here
    let regexTest = regex.test(valToLower);
    return !regexTest ? { "notSupportedFileType": true } : null;
  }

  validate(c: FormControl): { [key: string]: any } {
    return FileTypeValidator.validate(c);
  }

}

In your component,

this.form = new FormGroup({
        file: new FormControl("",    [FileTypeValidator.validate])
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.