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

elvalidator

v1.7.8

Published

Validate and Sanitize JSON objects.

Downloads

5

Readme

El Validator

Version NPM Downloads License

El Validator is a JSON Object validator and sanitizer. It's a great little tool for validating user input and sanitizing.

It's heavily inspired from the familiar Mongoose schema format with a few more features. (Note: El Validator doesn't attempt to strictly match the Mongoose validator)

  • 0 dependencies
  • Easy to use
  • Lightweight (8.51Kb minified)

Installation

$ npm install elvalidator --save

Or in the browser:

<script type="text/javascript" src="https://unpkg.com/elvalidator/elvalidator.min.js"></script>

Usage

import ElValidator from 'elvalidator';

// Set up the validator object
//let validator = new ElValidator(schema, options);
let validator = new ElValidator({
  name             : { type: String, required:true, trim:true, minLength:3 },
  age              : { type: Number, required:true, integer:true, min:18, max:100 },
  agreedTelemetry  : { type: Boolean, default:false },

  // Array example:
  tags             : [
    { type: String, minLength:3, lowercase:true, trim:true, match: /^[a-z0-9]+$/  }
  ],

  // Object example:
  settings	       : {
    darkMode    : { type: Boolean, default:false },
    codeEditor  : { type: String, required:false, default:'atom', enum:['atom', 'vstudio', 'notepad++'] },
  }
}, {
  // When disabled, the validator will go easy on the errors. (i.e. a number is provided instead of a string the number will be converted to a string instead of throwing an error)
  strictMode        : true,
  // Throw error when an unknown field is present
  throwUnkownFields : false,
  // Validate everything and then show big error message (vs. throw error as soon as an issue is detected)
  accumulateErrors  : false,
  // Whether to dismiss subschema objects when empty
  dismissEmptyObjects	: false
});

// Validate/Sanitize a data object
// If there's an error, it will be thrown. You can thus use a try ... catch block to process the errors.
var sanitizedData = await validator.validate({
  name        : 'Yassine',
  age         : 27,

  tags        : ['PROgrammer', 'javascript '],
  settings    : {
    darkMode  : false,
  },
  other       : 'unknown field',
});

console.log(sanitizedData);

/*
Outputs:
{
  name: 'Yassine',
  age: 27,
  agreedTelemetry: false,
  tags: [ 'programmer', 'javascript' ],
  settings: { darkMode: false, codeEditor: 'atom' }
}

*/

Schema Reference

String

{
	field	: {
		type		: String,
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: '', // If provided, the required field is not considered

		lowercase	: false, // Force string to lower case
		uppercase	: false, // Force string to UPPER CASE
		trim		: false, // Trim text (remove whitespace at the start and end of the string)
		minLength	: 3, // Minimum length of the string
		maxLength	: 15, // Maximum length of the string
		enum		: ['hello', 'world'], // Array with valid values for this field
		match		: /^(hello|world)$/i, // String must match with this regex

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Number

{
	field	: {
		type		: Number,
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: 0, // If provided, the required field is not considered

		integer		: false, // Force number to be an integer
		min			: 3, // Minimum value of the number
		max			: 15, // Maximum value of the number
		enum		: [5, 7, 12], // Array with valid values for this field

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Boolean

{
	field	: {
		type		: Boolean,
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: false, // If provided, the required field is not considered

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Array

{
	// With default options
	field	: [
		{ type: String } // Define the schema for the values this array should allow, in this case it accepts strings
	],

	// OR with options
	field	: {
		type		: [
			{ type: String } // Define the schema for the values this array should allow, in this case it accepts strings
		],
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: [], // If provided, the required field is not considered

		minEntries	: 0, // Minimum number of entries this array can hold
		maxEntries	: 10, // Maximum number of entries this array can hold
		uniqueValues: false, // Whether to filter out the values of the array to only return non-repeating values

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Object

This type allows you to accept Objects with arbitrary fields and no particular validation.

{
	field	: {
		type		: Object,
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: {}, // If provided, the required field is not considered

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Mixed

This type allows you to accept any type of input with no particular validation.

{
	field	: {
		type		: ElValidator.Types.Mixed,
		name		: "Field Name", // For cleaner error messages
		required	: false, // Is this a mandatory field?
		default		: null, // If provided, the required field is not considered
		enum		: [false, 5, 'auto'], // Array with valid values for this field

		validator	: async (value) => { // Manually validate/sanitize the value
			if(!value)
				throw new Error('Invalid value');
			return value;
		},
	}
}

Sub-Schema

{
	field	: {
		subField1	: { type: String },
		subField2	: { type: Number },
		subField3	: {
			type			: { type: String }, // Here type is a sub-sub-field and accepts strings
			subSubField2	: { type: Number },
		},
	}
}

$or operator

{
	field	: {
		$or	: [ // You can define different possible types for this particular field using the $or operator

			{ type: String, }, // field can either be a string,
			{ type: Number, min:0, max:10}, // a number between 0 and 10
			{ type: Number, min:100, max:1000, integer: true}, // or an integer between 100 and 1000
		],
		default		: '',
		required	: true,
	}
}

Built Ins

A few validators are available to make your life easier.

{
	url				: ElValidator.Builtins.Url,
	domainName		: ElValidator.Builtins.DomainName,
	email			: ElValidator.Builtins.Email,
	youtubeVideo	: ElValidator.Builtins.YoutubeVideo,
	vimeoVideo		: ElValidator.Builtins.VimeoVideo,
}

// will validate for:

{
	url				: 'https://www.example.com/index.html?query=param',
	domainName		: 'www.example.com',
	email			: '[email protected]',
	youtubeVideo	: 'https://www.youtube.com/watch?v=UNG7vNchvVQ',
	vimeoVideo		: 'https://vimeo.com/347119375',
}