isvalid is an asynchronous node.js library for validating and error correcting JavaScript data - which also includes JSON. It uses a very simple schema model - inspired by Mongoose.
- How to Use
- How it Works
- As Connect or Express Middleware
- Contributing
- License
isvalid uses a simple schema modal to specify how the data should be formatted. It supports generic validators for all types and type specific validators.
Usage:
await isvalid(dataToValidate, validationSchema, callback)Here's a simple example on how to use the validator.
const isvalid = require('isvalid');
isvalid(inputData, {
'user': { type: String, required: true },
'pass': { type: String, required: true }
}).then((data) => {
// Data was validated and valid data is available.
}).catch((err) => {
// A validation error occurred.
});– or using await/async.
const isvalid = require('isvalid');
let data = /* some data */
try {
data = await isvalid(data, {
'user': { type: String, required: true },
'pass': { type: String, required: true }
});
} catch(err) {
// A validation error occurred.
}
// data is validated.There is also build-in support for usage as an express or connect middleware – see the As Connect or Express Middleware section below for more information.
In order to be a complete schema, schemas must have at least the type, post/pre or equal validator. But, as you will notice throughout this document, many of the examples have none of them. Instead they just use type shortcuts.
This is because isvalid supports type shortcuts for all its supported types, and you are - if you want to help yourself - going to use them a lot. You can read more about type shortcuts in the designated section at the near-bottom of this document.
All errors are thrown (in promises).
- Wrong parameters throw the
Errortype. - Schema errors throw the
SchemaErrortype. - Validation errors throw the
ValidationErrortype.
The SchemaError contains a schema property which is the actual schema in which there is an error. It also has a message property with the description of the error that occurred.
The ValidationError contains three properties besides the message.
keyPathis an array indicating the key path in the data where the error occurred.schemais the schema that failed to validate.validatoris the name of the validator that failed.
These types are supported by the validator:
ObjectArrayStringNumberBooleanDate- Custom types
There are some validators that are common to all types, and some types have specific validators.
You specify the type like this:
{ type: String }or if type is your only validator, you can just do this:
StringIn the above example the input must be of type String.
All schemas must have at least a type, post/pre or equal validator.
There is more information about shortcuts in the Type Shortcuts section below.
These validators are supported by all types.
Defaults data to a specific value if data is not present in the input. It takes a specific value or it can call a function to retrieve the value.
Type: Any value or a function.
Example:
{
"email": { type: String, default: "[email protected]" }
}This tells the validator, that an email key is expected, and if it is not found, it should just assign it with (in this case) [email protected].
This works with all supported types - below with a boolean type:
{
"receive-newsletter": { type: Boolean, default: false }
}Now if the receive-newsletter key is absent in the data the validator will default it to false.
An asynchronous default function works using promises.
{
"created": {
type: Date,
default: async function() {
return new Date();
}
}
}A synchronous default function works the same way.
{
"created": {
type: Date,
default: function() {
return new Date();
}
}
}Values: true, false or 'implicit'.
required works a little like default. Except if the value is absent a ValidationError is thrown.
{ type: String, required: true }The above specifies that the data must be present and be of type String.
Example:
{
type: Object,
required: 'implicit',
schema: {
'user': { type: String, required: true }
'email': String
}
}The above example is to illustrate what 'implicit' does. Because the key user in the sub-schema is required, the parent object inherently also becomes required. If none of the sub-schemas are required, the parent object is also not required.
This enables you to specify that some portion of the data is optional, but if it is present - it's content should have some required keys.
See the example below.
{
type: Object,
required: false,
schema: {
'user': { type: String, required: true }
'email': String
}
}In the above example the data will validate if the object is not present in the input, even though user is required - because the parent object is explicitly not required. If the object - on the other hand - is present, it must have the user key and it must be of type String.
If
requiredis not specified, thenObjectandArraytypes are by default'implicit'. All other types are by default non-required. Alsorequiredis ignored ifdefaultis specified.
Type: Any
This validator allows for a static value. If this is provided the data must match the value of this validator.
This works with any type (also Object and Array) and a deep comparison is performed.
The
typevalidator becomes optional when usingequal.
Type: Object
errors are really not a validator - it allows you to customize the errors emitted by the validators. All validators have default error messages, but these can be customized in order to make them more user and context friendly.
An example below.
{
'username': {
type: String,
required: true,
match: /^[^\s]+$/,
errors: {
type: 'Username must be a string.',
required: 'Username is required.',
match: 'Username cannot contain any white spaces.'
}
}
}Now in case any of the validators fail, they will emit the error message specified - instead of the default built-in error message. The message property of ValidationError will contain the message on validation failure.
There is also a shortcut version for the errors validator. The above example can also be expressed like below.
{
'username': {
type: [String, 'Username must be a string.'],
required: [true, 'Username is required.'],
match: [/^[^\s]+$/, 'Username cannot contain any white spaces.']
}
}It might be a more convenient way, and it maps the errors to the same line as the validator, so it is more easy to read.
The schema validator of Object and Array types specifies the schema of their children. Objects have keys and schemas - arrays only have a single schema.
An example below of an object schema with a user key.
{
type: Object,
schema: {
'username': String
}
}And an example below of an array of strings.
{
type: Array,
schema: String
}There is also a shortcut version of describing objects and arrays. You can read more about that below in the Type Shortcuts section.
The Object type has only one specific validator - besides the common validators.
Type String of value: 'allow', 'deny' or 'remove'
This validator is used to control how unknown keys in objects are handled.
The validator has three options:
allowPass any unknown key onto the validated object.denyThrow aValidationErrorif object has unknown key.removeRemove the unknown key from the validated object.
Default is
deny.
The Array type has three specific validator - besides the common validators.
Type: Number or String
This ensures that an array has a specific length. This can be either a number or a range. The validator throws an error if the array length is outside the bounds of the specified range(s).
Examples:
{
type: Array,
len: 2,
schema: { … }
}An array that should have exactly 2 items.
{
type: Array,
len: '2-',
schema: { … }
}An array that should have at least 2 items.
{
type: Array,
len: '-2',
schema: { … }
}An array that should have a maximum of 2 items.
{
type: Array,
len: '2-5',
schema: { … }
}An array that should have at least 2 items and a maximum of 5 items.
{
type: Array,
len: '-2,5,8-',
schema: { … }
}Negative values can be wrapped in parentheses.
{
type: Array,
len: '(-2)-2',
schema: { … }
}It also supports non-integer values.
{
type: Array,
len: '(-2.2)-2.2',
schema: { … }
}An array that should have at least 2 items, exactly 5 items or 8 or more items.
Type: Boolean
This ensures that all elements in the array are unique - basically ensuring the array is a set. If two or more elements are the same, the validator throws an error.
Example:
{
type: Array,
unique: true,
schema: { … }
}The
uniquevalidator does a deep comparison on objects and arrays.
Type: Boolean
If the provided data is not an array - but it matches the sub-schema - this will wrap the data in an array before actual validation.
Example:
{
type: Array,
autoWrap: true,
schema: { … }
}If autoWrap is set to true and auto-wrap fails (the sub-schema cannot validate the data), then the type validator will emit a 'Must be of type Array.' error.
Default is
false.
The String type has four specific validator - besides the common validators.
Type: Boolean
This does not do any actual validation. Instead it trims the input in both ends - before any other validators are checked. Use this if you want to remove any unforeseen white spaces added at the beginning or end of the string by the user.
Type: String or Number
This ensures that the string's length is within a specified range. You can use the same formatting as Array's len validator described above (except it does not support ranges with negative values or non-integers).
Type: RegExp
This ensures that a string can be matched against a regular expression. The validator throws an error if the string does not match the pattern.
This example shows a string that must contain a string of at least one character of ASCII letters or decimal numbers:
{ type: String, match: /^[a-zA-Z0-9]+$/ }Type: Array
This is complimentary to match - as this could also easily be achieved with match - but it's simpler and easier to read. The validator ensures that the string can be matched against a set of values. If it does not, it throws a throws a ValidationError.
{ type: String, enum: ['none','some','all'] }In the above example the string can only have the values of none, some or all.
Remark that
enumis case sensitive.
The Number type has only one specific validator - besides the common validators.
Numberalso does automatic type conversion fromStringtoNumberwhere possible. You can read more about that and other automatic type conversions in the Automatic Type Conversion section below
Type: Numberor String
This ensures that the number is within a certain range. If not the validator throws an error.
The range validator uses the same formatting as the Array's len validator described above (except it does not support ranges with negative values or non-integers).
Type: String of value: 'allow', 'deny', 'round', 'floor', 'ceil'
This tells the validator how to handle non-integers.
The validator has five options:
'allow'Allow non-integer values.'deny'Throw aValidationErrorif the value is a non-integer.'round'Round value to nearest integer.'floor'Round to integer less than or equal to value.'ceil'Round to integer bigger than or equal to value.
Default is
'allow'.
Custom types are also supported, and all the generic validators work.
An example is below, where User is a custom class.
{
'user': { type: User, required: true }
}post can be used when the possibilities of the validation schema falls short. post basically outsources validation to a functions.
The
typevalidator becomes optional when usingpost. You can completely leave out any validation and just use apost(orpre) validator.
{
type: Object,
schema: {
'password': { type: String, required: true },
'passwordRepeat': String
},
'post': async (data, schema) => {
if (data.password !== data.passwordRepeat) {
throw new Error('Passwords must match.');
}
}
}In the above example we have specified an object with two keys - password and passwordRepeat. The validator first makes sure, that the object validates to the schema. If it does it will then call the post validator - which in this example throws an error if passwords do no match.
postfunctions works both by returning promises (async functions) and returning a value.
- If no value is returned the data does not change.
- Thrown errors are caught and converted to a
ValidationErrorinternally.
If you need to pass any options to your custom validator, you can do so by using a special options property of the schema, that becomes available when you use post (or pre - see below).
An example below.
{
'myKey': {
options: {
myCustomOptions: 'here'
},
post: function(data, schema) {
// schema.options will now contain whatever options you supplied in the schema.
// In this example schema.options is { myCustomOptions: 'here'}.
}
}
}The post validator also support an array of functions. Instead of providing just one function, you can provide an array of functions. Synchronous and asynchronous functions can be mixed and matched as necessary.
An example.
{
post: [
function(data, schema) {
data(null, myValidatedData);
},
async function(data, schema) {
return mySecondValidatedData
}
]
}If, though, any of the post validator functions throws an error, none of the rest of the post validators in the chain will get called, and isvalid will throw the error as a ValidationError.
The
postvalidator functions are called in order.
pre does the exact same thing as post described above, except it is called before any other validators are validated. This gives you a chance to transform the data and return it before the actual validation.
Some types can be specified using shortcuts. Instead of specifying the type, you simply just use the type. This works with Object and Array types.
In this document we've been using them extensively on Object examples, and the first example of this document should have looked like this, if it hadn't been used.
isvalid(inputData, {
type: Object,
schema: {
'user': { type: String, required: true },
'pass': { type: String, required: true }
}
}, function(err, validData) {
/*
err: Error describing invalid data.
validData: The validated data.
*/
});Object shortcuts are used like this:
{
'user': String
}and is the same as
{
type: Object,
schema: {
'user': { type: String }
}
}Which means that data should be an object with a user key of the type String.
Internally the library tests for object shortcuts by examining the absent of the
type,post/preorequalvalidators. So if you need objects schemas with validators for keys with those names, you must explicitly format the object usingtypeandschema- hence the shortcut cannot be used.
The same goes for arrays:
[String]is the same as
{
type: Array,
schema: String
}and is the same as
{
type: Array,
schema: { type: String }
}Which means the data must be an array of strings.
The others are a bit different. They are - in essence - a shortcut for the validator type. Instead of writing type you just specify the type directly. Available types are all the supported types of isvalid, namely Object, Array, String, Number, Boolean, Date and custom types.
An example below.
{
"favoriteNumber": Number
}The above example is really an example of two shortcuts in one - the Object and the Number type shortcut. The above example would look like the one below, if shortcuts had not been used.
{
type: Object,
schema: {
"favoriteNumber": { type: Number }
}
}If the schema has type Number and the input holds a String containing a number, the validator will automatically convert the string into a number.
Likewise will schemas of type Boolean will be automatically converted into a Boolean if a String with the value of true or false is in the data.
If the schema is of type Date and the input is a String containing an ISO-8601 formatted date, it will automatically be parsed and converted into a Date.
ISO-8601 is the date format that JSON.stringify(...) converts Date instances into, so this allows you to just serialize to JSON on - as an example - the client side, and then isvalid will automatically convert that into a Date instance when validating on the server side.
Connect and Express middleware is build in.
Usage:
isvalid.validate.body(schema)validatesreq.body.isvalid.validate.query(schema)validatesreq.query.isvalid.validate.param(schema)validatesreq.param.isvalid.validate.parameter(id, schema)validatesreq.paramas a route.
const { validate } = require('isvalid');
app.param('myparam', validate.param(Number)); // Validates parameter through param
app.post('/mypath/:myparam',
validate.parameter('myparam', Number), // Validates parameter through route.
validate.query({
'filter': String
}),
validate.body({
'mykey': { type: String, required: true }
}),
function(req, res) {
// req.param.myparam, req.body and req.query are now validated.
// - any default values - or type conversion - has been applied.
}
);If validation fails,
isvalidwill unset the validated content (req.bodywill becomeundefined). This is to ensure that routes does not get called with invalid data, in case a validation error isn't correctly handled. On the opposite,req.bodywill be set with the validated data (with transforms and automatic type conversion) if validation succeeds.
Contributions are much welcomed, and some great contributions by others have been provided throughout the years.
If you feel like something is missing, please send me a pull request. It is, though, important, that you you follow any new features up with unit tests.
MIT