npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

itf-validation

v1.0.0

Published

Description...

Downloads

2

Readme

It.Focus() Validation

Description...

Install

Types

  1. Add package to project.

Add validation package to dependencies in package.json

 "dependencies": {
   ...
    "validation": "git+https://gitlab.com/itdotfocus/itfformbuilder/itfformbuilder.git",
    ...
  },

and install new package

yarn install

Backend

  1. Add package to project.

Add validation package to dependencies in package.json

 "dependencies": {
   ...
    "validation": "git+https://gitlab.com/itdotfocus/itfformbuilder/itfformbuilder.git",
    ...
  },

and install new package

yarn install
  1. Add global pipe

Create ValidationPipe.ts in folder ./pipes/

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, Type } from '@nestjs/common';
import { Validation } from 'validation';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  transform = async (value: any, { metatype }: ArgumentMetadata) => {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    return await this.valid(value, metatype);
  }

  private toValidate = (metatype: Function): boolean => { // tslint:disable-line
    const types: Function[] = [String, Boolean, Number, Array, Object]; // tslint:disable-line
    return !types.includes(metatype);
  }

  private valid = async (value: any, metatype: Type<any>) => {
    const schema = Validation.getSchema(metatype);
    if (!schema) {
      return value;
    }
    return await schema.validate(value, { stripUnknown: true, abortEarly: false })
    .catch(err => {
      throw new BadRequestException(err.inner.map(this.filterMessages));
    })
  }

  filterMessages = ({ path, message}) => ({ path, message });
}

Use it globally by adding to main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '../pipes/validation.pipe';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3001);
}
bootstrap();

Note the correct import becaus nest.js has the same pipe.

import { ValidationPipe } from '../pipes/validation.pipe'; 
  1. Add form error functions to utils folder.
import { ApiErrorCode } from 'types';
import { BadRequestException, HttpStatus } from '@nestjs/common';

export const formError = (path: string, message: ApiErrorCode) => {
  throw new BadRequestException({ code: HttpStatus.BAD_REQUEST, message: [{ path, message }] });
}

export const formErrors = (message: { path: string, message: ApiErrorCode }[]) => {
  throw new BadRequestException({ code: HttpStatus.BAD_REQUEST, message });
}

Usage

Types usage

Create file with form validators First step is create validation class with @Form() decorator.

The post property of the argument is required. It defines path to send form (if we add edit mode then a parameter containing id will be added to this path for edit form).

The edit property defines path to get edit form details (parameter containing id will be added to this path by FrontEnd) and active edit mode.

@Form({ edit: '/offer/details', post: '/offer/add' })
export class OfferDto {}

Next step is add constructor with private argument formName with the default value witch is unique name of form (the best is class name);

constructor(private formName = 'OfferDto') {}

Last is add properties to validation class with for least one decorator.

Finally we have complete form to add and update data.

@Form({ edit: '/offer/details', post: '/offer/add' })
export class OfferDto {
  constructor(private formName = 'OfferDto') {}
  @IsDate()
  fromAt: Date;
  
  @IsDate()
  toAt: Date;
  
  @IsEnum(OfferCategory)
  category: OfferCategory;
  
  @IsEnum(OfferWages)
  wages: OfferWages;
}

Remember about export all form/validators like interfaces.

Back usage

One you have to do is add EP but there are a few things things you need to remember.

  1. Always use Post method (add or update). You can use two EP (add and update) but both with @Post().
  2. Type your body (or params or query) by validator from types package.
  @Post('/add/:offerId?')
  async addOrUpdateOffer(
    @Me() user: User,
    @Body() offerDto: OfferDto,
    @Param('offerId') offerId: string,
  ): Promise<null> {
    return this.offerService...;
  }

In Body of EP function is validated and transformated dto object.

Throw error

For throwing error user BadRequestException with ApiErrorCode.

throw new BadRequestException(ApiErrorCode.InvalidParams);

This Error will be displayed in toast.

Throw form error

For throwing field error use formError function form utils.

formError('email', ApiErrorCode.EmailInUse);

First argument is name of field, next is ApiErrorCode.

This Error will be displayed under input.

Throw form errors

For throwing field error use formErrors function form utils.

formError([{ path: 'email', message: ApiErrorCode.EmailInUse }, ...]);

This Errors will be displayed under inputs.

API

IsString

Define string type of property.

@IsString()

  • string IsRequired

Property can't be undefined, null or ''

@IsRequired()

  • string MinLength

Define min length of string.

@MinLength(value: number)

  • string MaxLength

Define max length of string.

@MaxLength(value: number)

  • string Email

Define property as email string;

@Email()

  • string Pwd

Define property as pwd string;

@Pwd(minLength?: number)

Default min length is 8

  • string Pwd2

Define property as repeated password string;

@Pwd2(pwdFieldName?: string)

Default password field name is pwd

IsNumber

Define number type of property.

@IsNumber()

  • number Min

Define min value of property.

@Min(value: number)

  • number Max

Define max value of property.

@Max(value: number)

IsBoolean

Define boolean type of property.

@IsBoolean()

IsDate

Define date type of property.

@IsDate()

  • date Min

Define min date.

@MIn(date: Date)

  • date Max

Define max date.

@Max(date: DAte)

IsArray

Define array type of property.

@IsArray(validationClass: any)

  • array Min

Define min array length.

@Min(length: number)

  • array Max

Define max array length.

@Max(length: number)

IsEnum

Value have to be defined enum.

@IsEnum<T>(myEnum: T);