top of page
  • Writer's pictureAppsec360 Team

Pattern: Input Validation - TypeScript

What is a Pattern?

A pattern for software development is a reusable solution to a common software design problem. It is a general approach that can be applied in various situations to solve similar problems. Patterns are usually documented in a standard format, which includes a name, a problem statement, a solution, and the consequences of applying the pattern.

Patterns are intended to provide developers with a way to describe and share proven solutions to common software development problems. They can help ensure that software is designed and developed in a way that is flexible, maintainable, and extensible.

There are various types of patterns, including:

  1. Creational patterns: These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

  2. Structural patterns: These patterns deal with object composition. They describe how objects are connected to one another to form larger structures.

  3. Behavioral patterns: These patterns deal with communication between objects, how objects collaborate with one another to perform tasks.

Patterns are typically classified into categories based on their scope and level of abstraction. For example, architecture patterns describe the overall structure of a software system, while design patterns describe solutions to smaller, more specific design problems within a system.

By using patterns, developers can reduce the amount of time and effort required to solve common problems, improve the quality of their software, and create more robust and maintainable code.


TypeScript focused input validation pattern


1. Define the Input Interface: Begin by defining an interface for the input you want to validate. The interface should include all the properties that are required for the input.

interface UserInput {
name: string;
email: string;
age: number;
}

2. Create a Validator Class: Create a class that will handle the validation of the input. This class should have a method for each type of validation you need to perform.

class Validator {
static validateName(name: string) {
// validation code for name }
static validateEmail(email: string) {
// validation code for email
}
static validateAge(age: number) {
// validation code for age
}
}

3. Validate the Input: In the class where you receive the input, call the validation methods of the validator class to ensure the input is valid.

function createUser(userInput: UserInput) {
  Validator.validateName(userInput.name);
  Validator.validateEmail(userInput.email);
  Validator.validateAge(userInput.age);

  // create user
}

4. Handling Validation Errors: When a validation error occurs, throw an error with a descriptive message. You can use a custom error class to handle validation errors.


class ValidationError extends Error {
constructor(message: string) {
    super(message);
    this.name = 'ValidationError';
  }
}

class Validator {
  static validateName(name: string) {
    if (!name) {
      throw new ValidationError('Name is required');
    }
  }

  static validateEmail(email: string) {
    // validation code for email
  }

  static validateAge(age: number) {
    // validation code for age
  }
}

5. Handling Multiple Errors: If there are multiple validation errors, collect all the errors and throw a single error with all the error messages.

class Validator {
  static validateName(name: string) {
    if (!name) {
      return 'Name is required';
    }

    if (name.length < 3) {
      return 'Name should be at least 3 characters';
    }

    return null;
  }

  static validateEmail(email: string) {
    // validation code for email
  }

  static validateAge(age: number) {
    // validation code for age
  }
}

function createUser(userInput: UserInput) {
  const errors = {
    name: Validator.validateName(userInput.name),
    email: Validator.validateEmail(userInput.email),
    age: Validator.validateAge(userInput.age),
  };

  const hasErrors = Object.values(errors).some((error) => error !== null);

  if (hasErrors) {
    const errorMessages = Object.entries(errors)
      .filter(([_, error]) => error !== null)
      .map(([field, error]) => `${field}: ${error}`);

    throw new ValidationError(errorMessages.join(', '));
  }

  // create user
}

This pattern can be extended and customized to meet the specific requirements of your application.













4 views0 comments

Comments


bottom of page