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

node-schema

v2.2.0

Published

A package for building javascript object schemas

Downloads

17

Readme

#Schema A simple way to build javascript schemas for validating objects.

###Installation npm install node-schema

###Schemas node-schema focuses on simplicity and flexibility. Its great when you need ease of use, custom validation functions, or custom messages returned from validation.

Schemas can be used in node or in the browser (using something like browserify).

####Basic Usage Schemas can be used to validate simple values.

var Schema = require('node-schema');
var str = require('string-validator');

var valueSchema = Schema({
  'must have at least 5 characters': str.isLength(5),
  'can only contain numbers and letters': str.matches(/^[a-zA-Z0-9]*$/)
});

valueSchema.validate('').then(function(errors){
  // errors => [ 'must have at least 5 characters' ]
});
valueSchema.validate('myUser?').then(function(errors){
  // errors => [ 'can only contain numbers and letters' ]
});
valueSchema.validate('myValidUser').then(function(errors){
  // errors => null
});

In value schemas, the keys are messages and the values are simple validating functions. This means that it is very easy to create custom validations.

The validating functions take 3 arguments:

  • value: the value to validate
  • [options]: the options passed to the validate function
  • [object]: the object containing the value
var valueSchema = Schema({
  'must have at least 5 characters': function(value){
    return value.length >= 5;
  },
  'can only contain numbers and letters': function(value){
    return /^[a-zA-Z0-9]*$/.test(value);
  })
});

valueSchema.validate('').then(function(errors){
  // errors => [ 'must have at least 5 characters' ]
});
valueSchema.validate('myUser?').then(function(errors){
  // errors => [ 'can only contain numbers and letters' ]
});
valueSchema.validate('myValidUser').then(function(errors){
  // errors => null
});

Object schemas provide the ability to nest fields.

var userSchema = Schema({
  username: {
    'must have at least 5 characters': str.isLength(5),
    'can only contain numbers and letters': str.matches(/^[a-zA-Z0-9]*$/)
  }
});

userSchema.validate({username: ''}).then(function(errors){
  // errors => { username: [ 'must have at least 5 characters' ] }
});
userSchema.validate({username: 'myUser?'}).then(function(errors){
  // errors => { username: [ 'can only contain numbers and letters' ] }
});
userSchema.validate({username: 'myValidUser'}).then(function(errors){
  // errors => null
});

Validating functions can use the object argument to check the value of sibling fields.

var passwordSchema = Schema({
  password: {
    'must contain at least 5 characters': str.isLength(5)
  },
  passwordCheck: {
    'must match password': function(value, options, object){
      return value == object.password;
    }
  }
});

passwordSchema.validate({
  password: 'tough',
  passwordCheck: 'weak'
}).then(function(errors){
  // errors => { passwordCheck: [ 'must match password' ] }
});

Schema objects can be nested inside object schemas.

var postSchema = Schema({
  user: userSchema,
  post: {
    'must contain between 25 and 500 characters': str.isLength(25, 500)
  }
});

postSchema.validate({
  post: 'this is my first post',
  user: {
    username: 'invalid?'
  }
}).then(function(errors){
  /* errors =>
  {
    user: {
      username: [ 'can only contain numbers and letters' ]
    },
    post: [ 'must contain between 25 and 500 characters' ]
  }
  */
});

####Advanced Usage #####Required Fields By default, all fields are required. The error message on missing fields can be changed globally or on a field by field basis.

var requiredSchema = Schema({
  required: {'must contain at least 5 characters': str.isLength(5)}
});

// default
requiredSchema.validate({}).then(function(errors){
  // errors => {required: ['is required']}
});

// global change (using options)
requiredSchema.validate({}, {isRequiredMessge: 'must exist'})
.then(function(errors){
  // errors => {required: ['must exist']}
});

var Field = Schema.Field;
// per field
requiredSchema = Schema({
  required: Field.required('is a required field', {
    'must contain at least 5 characters': str.isLength(5)
  })
});

requiredSchema.validate({}).then(function(errors){
  // errors => {required: ['is a required field']}
});

// No need for a sub-schema definition if the field can be anything
requiredSchema = Schema({
  required: Field.required('is a required field')
});

requiredSchema.validate({}).then(function(errors){
  // errors => {required: ['is a required field']}
});

#####Optional Fields Fields can be made optional

var Field = Schema.Field;

var maybeSchema = Schema({
  maybe: Field.optional({
    'must contain at least 5 characters': str.isLength(5)
  })
});

maybeSchema.validate({}).then(function(errors){
  // errors => null
});

maybeSchema.validate({maybe: '1234'}).then(function(errors){
  // errors => {maybe: ['must contain at least 5 characters']}
});

#####Asynchronous Validation A promise can be returned from a validation function for asynchronous validation.

var fs = require('fs');

var asynchronousSchema = Schema({
  file: {
    'file must exist': function(file){
      return new Promise(function(resolve){
        fs.exists(file, resolve);
      });
    }
  }
});

###License (MIT)

MIT License
Copyright (c) 2014 Adam Nalisnick

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.