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

easyvalid

v1.1.0

Published

Easy Validator For Fields and Models

Downloads

14

Readme

CLI

Módulo Javasctipt/Typescript que permite validar facilmente datos en objetos con estructuras complejas.

Descripción

easyvalid permite implementar muy facilmente validaciones de datos de cualquier tipo y con cualquier clase de condiciones.

Instalación

npm install -s easyvalid

Ejemplo de Uso simple en Typescript

import { EasyValid, ValueValidator} from 'easyvalid';
import { EasyError } from 'easyerror';

// **************** Definimos nuestros validadores personalizados ************************

//Validador de Email (ejemplo, no usar en producción)
const emailValidator : ValueValidator<string> = (value, conditions) => {
  if(typeof value !== 'string')
    throw new EasyError('Email inválido, No es un string');
  if(value.indexOf('@') > 0){
     return value; //Retornar el valor validado
  } else {
    throw new EasyError('Email inválido, No se encontró @');
  }
} 

//Validador de valores numéricos
const numberValidator : ValueValidator<number> = (value, conditions) => {
  //Verificar el tipo de dato de entrada
  if(typeof value != 'number' && typeof value != 'string') 
    throw new EasyError(`Número inválido`);
  //Verificar que es un valor numérico
  let out = +value;
  if(isNaN(out)) throw new EasyError('Número inválido');
  //Verificar condiciones adicionales
  if(conditions.length >= 1 && out < +conditions[0])
    throw new EasyError(`Número inválido, es menor que ${conditions[0]}`);
  if(conditions.length >= 2 && out > +conditions[1])
    throw new EasyError(`Número inválido, es mayor que ${conditions[1]}`);
  return out; //Retornar el valor validado
}


//*******************************  Creamos el Validador *********************************

const easyValid = new EasyValid({
  'number' : numberValidator,
  'email' : emailValidator
});


// ************** Creamos una plantilla del tipo de dato a validar *************** 

//Plantilla de un objeto simple
const template1 = easyValid.parseTemplate(
  {
    edad : 'number',
    porcentaje : 'number:0:100', //tipo con condiciones
    info : {
      pais : 'string',
      email : 'email'
    }
  }
);


// ********************** Validamos usando la plantilla ************************

//Objeto no valido
const noValid = {
  edad : '20',
  porcentaje : 40,
  info : {
    pais : 'colombia',
    email : 'asdjajdasd'
  }
};

//Objeto valido
const valid = {
  edad : '20',
  porcentaje : 40,
  info : {
    pais : 'colombia',
    email : '[email protected]'
  }
}

try {
  console.log('Valid Data:');
  const validData = easyValid.validate(valid, template1);  
  console.dir(validData);
  console.log()

  console.log('Invalid Data:');
  const invalidData = easyValid.validate(noValid, template1);  
  console.dir(invalidData);
}catch(e){
  if(e instanceof EasyError)
    console.error(`Error In ${e.getTrace()} : ${e.message}`);
  else 
    console.error(`Error : ${e.message}`);
  console.log();
}

Uso avanzado

EasyValid incluye por defecto cuatro validatores : numeric, string, null, undefined que realizan validaciones básicas para dato numerico, cadena de caracteres, valor null y datos indefinidos. los validadores por defecto y los personalizados pueden usarse en conjunto para más posibilidades de validación. Pueden generarse plantillas de validación de modelos complejos de datos.

// **************  plantillas Avanzadas *************** 

//Plantilla de un array
const template2 = easyValid.parseTemplate(
  [
    {
      nombre : 'string',
      //Pueden usarse Varios validadores, será valido si cumple con almenos uno
      edad : 'number|null|undefined'
    }
  ]
);


//Plantilla de un Modelo 
class Usuario {
  //Se debe definir $template en la clase como estático
  static $template = {
    nombre : 'string',
    email : 'email|undefined'
  }

  email : string;

  constructor(
    public nombre : string
  ){ }

  setEmail(email){
    this.email = email;
  }
}

const template3 = easyValid.parseTemplate(Usuario);


//Plantilla compleja (Puede realizarce cualquier combinación)

class Businessman {
  static $template = {
    user : Usuario,
    hijos : [ 
      {
        nombre : 'string',
        edad : 'number'
      }
    ],
    socios : [ Usuario ]
  }

  user : Usuario;
  hijos : any[];
  socios : Usuario[]
}

const template4 = easyValid.parseTemplate(Businessman);


const toValidate = {
  user : {
    nombre : 'Nombre del usuario',
  },
  hijos : [
    { nombre : 'Hijo 1', edad : 10 },
    { nombre : 'Hijo 2', edad : 12 },
    { nombre : 'Hijo 3', edad : 5 }
  ],
  socios : [new Usuario('socio 1'), new Usuario('socio 2')]
};


try {
  console.log('Valid complex Data:');
  const validData : Businessman = easyValid.validate(toValidate, template4);  
  console.dir(validData);
  console.log()
  
  validData.user.setEmail('[email protected]');
  console.dir(validData.user);
  console.log()
}catch(e){
  if(e instanceof EasyError)
    console.error(`Error In ${e.getTrace()} : ${e.message}`);
  else 
    console.error(`Error : ${e.message}`);
  console.log();
}