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 = ;var str = ; var valueSchema = ; valueSchema;valueSchema;valueSchema;
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
var valueSchema = ; valueSchema;valueSchema;valueSchema;
Object schemas provide the ability to nest fields.
var userSchema = ; userSchema;userSchema;userSchema;
Validating functions can use the object argument to check the value of sibling fields.
var passwordSchema = ; passwordSchema;
Schema objects can be nested inside object schemas.
var postSchema = ; postSchema;
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 = ; // defaultrequiredSchema; // global change (using options)requiredSchema; var Field = SchemaField;// per fieldrequiredSchema = ; requiredSchema; // No need for a sub-schema definition if the field can be anythingrequiredSchema = ; requiredSchema;
Optional Fields
Fields can be made optional
var Field = SchemaField; var maybeSchema = ; maybeSchema; maybeSchema;
Asynchronous Validation
A promise can be returned from a validation function for asynchronous validation.
var fs = ; var asynchronousSchema = ;
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.