Friday, July 28, 2023

Angular TypedForm: Building Strongly Typed Forms in Angular

Angular typed form

Angular is a powerful framework used for developing modern web applications, where forms play a critical role in data processing and user interactions. To ensure a smooth user experience and maintain data integrity, effective handling of form data is essential. Angular provides various mechanisms for form management, and one of the most robust approaches is utilizing Angular TypedForm.

What is Angular TypedForm?

Angular TypedForm is a library specifically designed for Angular that enhances the standard Angular Reactive Forms with strong typing capabilities. This means that you can define your form models using TypeScript interfaces or classes, resulting in more robust and maintainable forms with fewer errors.

Benefits of Angular TypedForm:
1.Type Safety: TypedForm allows you to define the structure of your form data using TypeScript interfaces or classes. By doing so, the form data will adhere to the specified types, preventing runtime errors caused by incorrect data.
2.Code Completion and IntelliSense: Utilizing TypeScript provides the advantage of code autocompletion and IntelliSense in modern code editors. This feature streamlines form development by providing suggestions for available properties and methods of the form model directly from the editor.
3.Refactoring Support: Defining the form model as a TypeScript interface or class makes refactoring more manageable. Any changes, such as renaming or modifying a property in the form model, will be automatically reflected throughout your codebase.

Saturday, April 8, 2023

Angular Reactive Form - File validators for File Upload

File upload fuctionality is a very common use case in applications. Whenever we allow users to upload files to server, we should have both client side and server side validation. Most likely we validates file size and file extension.
In this post, we are going to see the validators for File Upload functionality in Aangular Reactive Form.

file-validations.ts

In file-validations.ts, we have three validators- FileExtension validator, FileMaxSize validator and FIle Minimum size validator.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
const FILE_MAX_SIZE = 2048;
const FILE_MIN_SIZE = 1024;
export class FileValidations {
  public static fileExtensionValidator(
    acceptedExtensions: string[]
  ): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (control.value) {
        const ext = control.value.split('.').pop();
        if (!acceptedExtensions.includes(ext)) {
          return {
            fileExtension: {
              acceptedExtensions: acceptedExtensions,
              actualExtension: ext,
            },
          };
        }
      }
      return null;
    };
  }
  public static fileMaxSizeValidator(files: FileList): ValidatorFn {
    return (): ValidationErrors | null => {
      if (files.length > 0) {
        if (Math.round(files[0].size / 1024) > FILE_MAX_SIZE) {
          return {
            fileMaxSize: {
              requiredSize: `${Math.round(FILE_MAX_SIZE) / 1024}MB`,
              actualSize: `${Math.round(
                Math.round(files[0].size / 1024) / 1024
              )}MB`,
            },
          };
        }
      }
      return null;
    };
  }
  public static fileMinSizeValidator(files: FileList): ValidatorFn {
    return (): ValidationErrors | null => {
      if (files.length > 0) {
        if (Math.round(files[0].size / 1024) < FILE_MIN_SIZE) {
          return {
            fileMinSize: {
              requiredSize: `${Math.round(FILE_MIN_SIZE) / 1024}MB`,
              actualSize: `${Math.round(
                Math.round(files[0].size / 1024) / 1024
              )}MB`,
            },
          };
        }
      }
      return null;
    };
  }
}
^ Scroll to Top