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

@secjs/validator

v1.0.2

Published

> Validate payloads from any NodeJS project.

Downloads

5

Readme

Validator ✅

Validate payloads from any NodeJS project.

GitHub followers GitHub stars

The intention behind this repository is to maintain a payload validator package to use inside any NodeJS project.

Installation

To use the high potential from this package you need to install first this other packages from SecJS, it keeps as dev dependency because one day @secjs/core will install everything once.

npm install @secjs/exceptions

Then you can install the package using:

npm install @secjs/validator

Validator

Use Validator class to extend in your validation classes

import { Validator } from '@secjs/validator'

export class UserValidator extends Validator {
  get schema() {
    return {
      name: 'string|required',
      email: 'email|required',
    }
  }

  get updateSchema()  {
    return {
      name: 'string',
      email: 'string',
    }
  }
}

const userValidator = new UserValidator()

try {
  const validatedData = await userValidator.validate({ 
    name: 'João', 
    email: '[email protected]' 
  }, 'schema')
  
  return validatedData
} catch(error) {
  // All the validation errors found
  throw error
}

Nice validator options

Fail on first and clean the data

import { Validator } from '@secjs/validator'

export class UserValidator extends Validator {
  get validateAll() {
    return false
  }
  
  get removeAdditional() {
    return true
  }
  
  get schema() {
    return {
      name: 'string|required',
      email: 'email|required',
    }
  }
}

const userValidator = new UserValidator()

try {
  const validatedData = await userValidator.validate({ 
    name: 'João', 
    email: '[email protected]', 
    additionalProp: 'hello' 
  }, 'schema')

  return validatedData // { name: 'João', email: '[email protected]' } without additionalProp
} catch(error) {
  // Only the first validation error found
  throw error 
  // [
  //   {
  //     message: 'required validation failed on name',
  //     validation: 'required',
  //     field: 'name',
  //   }
  // ]
}

Custom error messages

Use custom error messages and Internationalization support

import { Validator } from '@secjs/validator'

export class UserValidator extends Validator {
  get messages() {
    return {
      email: '{{ field }} is not a valid email',
      // pt-br
      'name.required': '{{ field }} é obrigatório para criar um usuário'
    }
  }
  
  get schema() {
    return {
      name: 'string|required',
      email: 'email|required',
    }
  }
}

const userValidator = new UserValidator()

try {
// try implementation...
} catch(error) {
  throw error 
  // [
  //   {
  //     message: 'name é obrigatório para criar um usuário',
  //     validation: 'required',
  //     field: 'name',
  //   },
  //  {
  //     message: 'email is not a valid email',
  //     validation: 'email',
  //     field: 'email',
  //   }
  // ]
}

Sanitizer

Use Sanitizer class to extend in your validation classes

import { Sanitizer } from '@secjs/validator'

export class UserSanitizer extends Sanitizer {
  get schema() {
    return {
      email: 'trim|lower_case',
    }
  }

  get updateSchema() {
    return {
      email: 'trim|lower_case',
    }
  }
}

const userSanitizer = new UserSanitizer()

userSanitizer.sanitize({ 
  email: '[email protected]      ' 
}, 'schema') // Return the object with sanitizations implemented
// { email: '[email protected]' }

Extend Validator and Sanitizer

Extend validation and sanitizer rules

import * as he from 'he'
import { Validator, Sanitizer } from '@secjs/validator'

export class ExtendValidator {
  protected validator: Validator
  
  constructor() {
    this.validator = new Validator()
    
    this.validator.extendAsync('unique', this.unique)
  }

  // Returning false will fail the validation
  unique = async (data: any, field: string, args: string[]) => {
    const repository = this.getRepository(args[0])

    const model = await repository.getOne(null, {
      where: { [field]: this.validator.getValue(data, field) },
    })

    return !model
  }
}

export class ExtendSanitizer {
  protected sanitizer: Sanitizer

  constructor() {
    this.sanitizer = new Sanitizer()

    this.sanitizer.extend('escape', this.escape)
  }

  escape = async (data: any, field: string, args: string[], config: any) => {
    let fieldValue = this.sanitizer.getValue(data, field)
    
    if (typeof (fieldValue) !== 'string') {
      return
    }

    this.sanitizer.patchValue(data, field, he.escape(fieldValue))
  }
}

More rules

This project is using indicative package to implement class Sanitizer and Validator if you want to check all the validation and sanitizer rules check indicative documentation.


License

Made with 🖤 by jlenon7 :wave: