Isvalid
Asynchronous JavaScript validation library for Node.js and browsers.
Install / Use
/learn @trenskow/IsvalidREADME
isvalid
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.
Table of Content
- How to Use
- How it Works
- As Connect or Express Middleware
- Contributing
- License
How to Use
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)
Example
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.
How it Works
A Note on the Examples in this Document
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.
Errors
All errors are thrown (in promises).
- Wrong parameters throw the
Errortype. - Schema errors throw the
SchemaErrortype. - Validation errors throw the
ValidationErrortype.
SchemaError
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.
ValidationError
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.
Supported Types
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:
String
In 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.
Validators Available to All Types
These validators are supported by all types.
default
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.
Static Values
Example:
{
"email": { type: String, default: "email@not.set" }
}
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@not.set.
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.
Asynchronous Functions
An asynchronous default function works using promises.
{
"created": {
type: Date,
default: async function() {
return new Date();
}
}
}
Synchronous Functions
A synchronous default function works the same way.
{
"created": {
type: Date,
default: function() {
return new Date();
}
}
}
required
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.
Implicitly Required
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.
equal
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.
errors (Custom Error Messages)
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.
Error Shortcuts
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.
