0.14.0 • Published 2 years ago

@vodyani/validator v0.14.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Vodyani validator

🔍 "validator" offers simple-to-use decorators and validation techniques.

Npm Npm Npm License codecov Workflow semantic-release: angular

Installation

npm install @vodyani/validator

Usage

Class Validator

The core functionality of @vodyani/validator comes from class-validator.

Use decorators to complete the verification of internal class properties.

Before we begin, let's look at a basic example.

Next, let's see what awesome features @vodyani/validator offers.

FeaturesTypeDescription
toValidateClassmethodValidate the class structure against the incoming classes and data.
ArgumentValidatordecoratorMethod validator, needs to be used in combination with other parameter decorators.
RequireddecoratorSpecify a method parameter that must be passed in, or throw an exception.
ValidateddecoratorSpecify a method parameter for the method that needs to be executed in the validator.
EachValidateddecoratorSpecify a method parameter that needs to be executed in the validator, and this parameter needs to be looped through.
CustomValidateddecoratorValidate parameters using custom validators.

toValidateClass

Validate the class structure against the incoming classes and data.

Params

paramtypedescription
typeClassThe classes that need to be validated.
dataobjectThe data that needs to be validated.
optionsClassValidateOptionsThe rules options for data conversion and validation.

ClassValidateOptions

see:

export interface ClassValidateOptions {
  /**
   * The class-validator options.
   *
   * It's highly advised to set forbidUnknownValues: true as it will prevent unknown objects from passing validation.
   */
  validate?: ValidatorOptions;
  /**
   * The class-transformer options. (`excludeExtraneousValues` is enabled by default)
   */
  transform?: ClassTransformOptions;
}

Return

string (error message)

Example

Tips:

  • The class-transformer options, excludeExtraneousValues is enabled by default !
  • About the optional judgment in the example @ValidateIf.
import { Expose } from '@vodyani/transformer';
import { toValidateClass, isValid, IsNumber, IsString, IsNotEmpty, ValidateIf } from '@vodyani/validator';

class User {
  @Expose()
  @IsNumber({ allowNaN: false }, { message: 'id is not valid !' })
  public id: number;

  @Expose()
  @IsString({ message: 'name is not valid !' })
  @ValidateIf((user: User) => isValid(user.name))
  public name?: string;
}

toValidateClass(User, { id: '1' }) // Error: id is not valid !
toValidateClass(User, { id: 1, name: 1 }) // Error: name is not valid !

ArgumentValidator

Method validator, needs to be used in combination with other parameter decorators.

Tips:

Can only be bound to asynchronous methods !

Params

paramtypedescription
optionsArgumentValidateOptionsThe argument validator options.

ArgumentValidateOptions

see:

/**
 * The class-validator options.
 *
 * It's highly advised to set forbidUnknownValues: true as it will prevent unknown objects from passing validation.
 */
export interface ArgumentValidateOptions extends ClassValidateOptions {
  /** The error mode */
  Mode?: Class<Error>;
}

Required

Specify a method parameter that must be passed in, or throw an exception.

Tips:

  • This is a parameter Decorator.
  • Must be used in conjunction with the method decorator: ArgumentValidator !

Params

paramtypedescription
messagestringThe error message. (default: missing required argument !)

Example

import { ArgumentValidator, Required } from '@vodyani/validator';

class UserRecord {
  @ArgumentValidator()
  async getInfo(@Required() id: number) {
    return {
      id,
      name: 'demo',
    };
  }
}

const record = new UserRecord();

await record.getInfo(null); // Error: missing required argument !

Validated

Specify a method parameter for the method that needs to be executed in the validator.

Tips:

  • This is a parameter Decorator.
  • Must be used in conjunction with the method decorator: ArgumentValidator !

Example

import { Expose } from '@vodyani/transformer';
import { ArgumentValidator, IsNumber, Validated } from '@vodyani/validator';

class User {
  @Expose()
  @IsNumber({ allowNaN: false }, { message: 'id is not valid !' })
  public id: number;
}

class UserRecord {
  @ArgumentValidator()
  async saveInfo(@Validated() user: User) {
    return user;
  }
}

const record = new UserRecord();

await record.saveInfo({ id: null }); // Error: id is not valid !

EachValidated

Specify a method parameter that needs to be executed in the validator, and this parameter needs to be looped through.

Tips:

  • This is a parameter Decorator.
  • Must be used in conjunction with the method decorator: ArgumentValidator !

Params

paramtypedescription
typeClassThe classes that need to be validated.

Example

import { Expose } from '@vodyani/transformer';
import { ArgumentValidator, EachValidated, IsNumber } from '@vodyani/validator';

class User {
  @Expose()
  @IsNumber({ allowNaN: false }, { message: 'id is not valid !' })
  public id: number;
}

class UserRecord {
  @ArgumentValidator()
  async saveAll(@EachValidated() users: User[]) {
    return users;
  }
}

const record = new UserRecord();

await record.saveAll([{ id: null }]); // Error: id is not valid !

CustomValidated

Validate parameters using custom validators.

Tips:

  • This is a parameter Decorator.
  • Must be used in conjunction with the method decorator: ArgumentValidator !

Params

paramtypedescription
validator(data: any) => booleanThe validation function.
messagestringThe error message.

Example

import { ArgumentValidator, CustomValidated, isValid } from '@vodyani/validator';

class UserRecord {
  @ArgumentValidator()
  async getInfo(@CustomValidated(isValid, 'error')) id: number) {
    return {
      id,
      name: 'demo',
    };
  }
}

const record = new UserRecord();

await record.getInfo(null); // Error: error

Method Validator

paramdescription
isValidChecks if the data is non-empty.
isValidIPChecks if the data is valid ip.
isValidURLChecks if the data is valid url.
isValidArrayChecks if the data is non-empty array.
isValidStringChecks if the data is non-empty string.
isValidNumberChecks if the data is non-empty number (Also it will not be NAN or plus or minus infinity).
isValidObjectChecks if the data is non-empty object.
isValidStreamChecks if the data is stream.
isValidBufferChecks if the data is buffer.

License

Vodyani validator is MIT licensed.