Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5430

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T09:12:07+00:00 2024-11-27T09:12:07+00:00

Image validation for Angular

  • 61k

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.

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

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.

interface ImageValidatorFn {   (image: HTMLImageElement): ValidationErrors | null; } 
Enter fullscreen mode Exit fullscreen mode

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

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;   } } 
Enter fullscreen mode Exit fullscreen mode

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

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();   }; }; 
Enter fullscreen mode Exit fullscreen mode

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:

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));   }; } 
Enter fullscreen mode Exit fullscreen mode

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:

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; } 
Enter fullscreen mode Exit fullscreen mode

Great! Let's make it work.

Step 4. Usage

For example write a simple size validator.

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;   }; } 
Enter fullscreen mode Exit fullscreen mode

Ratio validation example

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

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; } 
Enter fullscreen mode Exit fullscreen mode

Example

If you're interested in exploring my example further, you can find it on Stackblitz by following this link.

angularfrontendjavascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers
  • Author

    Refactoring for Efficiency: Tackling Performance Issues in Data-Heavy Pages

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.