Image validation for Angular
Tags: angular, javascript, frontend, webdev
Published: 2023-04-17 21:56:21

Uploading images is a common feature in many web applications. However, it's important to ensure that the uploaded
images meet certain criteria, such as the correct file type, size, and aspect ratio.
In this article, we'll explore how to use an asynchronous validator to validate images in an Angular application.

The code provided is an example of how to implement a validator for images in your application.

{% embed https://stackblitz.com/edit/angular-nyvkfc?file=src/main.ts %}

```typescript
@Component({
  templateUrl: 'hero.component.html',
  template: `<input [formConrol]="fileControl" />`,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HeroComponent {
    readonly fileControl = new FormControl(null, null, [imageRatioAsyncValidator(['16:9'])])
}
```

Lets deep dive how to write that validator.

## Getting started

#### Step 1. Base

To implement an image validator, we first define an ImageValidatorFn interface that describes callback function of validator.

```typescript
interface ImageValidatorFn {
  (image: HTMLImageElement): ValidationErrors | null;
}
```

Then create an `imageAsyncValidator` function that takes an `ImageValidatorFn` and returns our `AsyncValidatorFn` that can be used in an Angular form control.

```typescript
export function imageAsyncValidator(
  imageValidatorFn: ImageValidatorFn,
): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    if (!control.value) {
      return of(null);
    }

    // Support multiple uploads
    const files: File[] = Array.isArray(control.value)
      ? control.value
      : [control.value];


    return null;
  }
}
```

#### Step 2. How to read uploaded file?

Each selected file using the FileReader API, loads it as an Image, and invokes the `ImageValidatorFn` on it

```typescript
const reader = new FileReader();
reader.readAsDataURL(file);

reader.onload = event => {
  const result = event.target?.result;

  if (!result) {
    observer.next(null);
    observer.complete();
    return;
  }

  const image = new Image();

  image.src = result as string;
  image.onload = () => {
    observer.next(imageValidatorFn(image));
    observer.complete();
  };
};
```



#### Step 3. Setup validator

Now that we've gained an understanding of how to read a file, let's move forward with implementing that solution in our validator.

Here's the code for the final `imageAsyncValidator` function:

```typescript
interface ImageValidatorFn {
  (image: HTMLImageElement): ValidationErrors | null;
}

export function imageAsyncValidator(
  imageValidatorFn: ImageValidatorFn,
): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    if (!control.value) {
      return of(null);
    }

    // Support multiple uploads
    const files: File[] = Array.isArray(control.value)
      ? control.value
      : [control.value];

    const fileValidation$: Observable<ValidationErrors | null> = files.map(
      (file: File) =>
        new Observable<ValidationErrors | null>(observer => {
          const reader = new FileReader();
          reader.readAsDataURL(file);

          reader.onload = event => {
            const result = event.target?.result;

            if (!result) {
              observer.next(null);
              observer.complete();
              return;
            }

            const image = new Image();

            image.src = result as string;
            image.onload = () => {
              observer.next(imageValidatorFn(image));
              observer.complete();
            };
          };
        }),
    );

    return combineLatest(fileValidation$).pipe(map(combineValidationErrors));
  };
}
```

We combine the results of all the validations using the `combineLatest` operator from RxJS,
which emits a new array of results whenever any of the observables it's subscribed to emits a new value.

We also define a `combineValidationErrors` function that merges all the `ValidationErrors` objects into a single object.

Here's the updated code for the `combineValidationErrors` function:

```typescript
function combineValidationErrors(
  errors: Array<ValidationErrors | null>,
): ValidationErrors | null {
  const combinedErrors: ValidationErrors = errors.reduce<ValidationErrors>(
    (acc, curr) => {
      if (curr) {
        return {...acc, ...curr};
      } else {
        return acc;
      }
    },
    {},
  );

  if (Object.keys(combinedErrors).length === 0) {
    return null;
  }

  return combinedErrors;
}
```

Great! Let's make it work.

#### Step 4. Usage

For example write a simple size validator.

```typescript
const fileControl = new FormControl(null, null, [imageWidthValidatorFn(200)])

function imageWidthValidatorFn(maxWidth: number): ImageValidatorFn {
  return (image: HTMLImageElement) => {
    if (image.width > maxWidth) {
      return { imageWidth: `Image width limit ${maxWidth}px` };
    }

    return null;
  };
}
```

## Ratio validation example

I'd also like to provide an additional example by sharing my RatioValidator with you.

```typescript
type Ratio =
  | '1:1'
  | '4:3'
  | '16:9'
  | '3:2'
  | '5:4'
  | '8:1'
  | '2:35'
  | '1:85'
  | '21:9'
  | '9:16';

export const imageRatioAsyncValidator = (allowedRatio: Ratio[]) =>
  imageAsyncValidator(image => {
    const {width, height} = image;
    const imageRatio = getAspectRatio(width, height);

    if (allowedRatio.includes(imageRatio as Ratio)) {
      return null;
    }

    return {
      imageRatio: `${imageRatio
        .toString()
        .replace(
          /\./,
          ':',
        )} is not allowed ratio. Please upload image with allowed ratio ${allowedRatio
        .join(',')
        .replace(/\./g, ':')}.`,
    };
  });

function getAspectRatio(width: number, height: number): Ratio {
  const calculate = (a: number, b: number): number => (b === 0 ? a : calculate(b, a % b));

  return `${width / calculate(width, height)}:${
    height / calculate(width, height)
  }` as Ratio;
}
```

### Example

If you're interested in exploring my example further, you can find it on Stackblitz by following this [link](https://stackblitz.com/edit/angular-nyvkfc?file=src/main.ts).