jsnvl
The simple Javascript Object Validator.
Notes
JSNVL is an incredibly simple Javascript Object Validator, and is designed for simple schema validation. There are other libraries available if you require more complicated validation, but this should be enough for most use cases.
Usage
- Install from NPM,
npm install jsnvl
import JSNVL from "jsnvl";
JSNVL(object, schema, options)
- object (Object):
- The JS object you wish to validate.
- schema (Object):
- The schema you wish to validate the object against.
- options (Object, optional):
- ignoreExcessKeys (Boolean, Default
false
): Ignores any keys present on the object that are NOT present on the schema. - ignoreThrownErrors (Boolean, Default
false
): Ignores any errors thrown by JSNVL. JSNVL throws errors on implementation issues, such as passing an invalid schema. This will convert those errors to afalse
return. - silenceLogs (Boolean, Default
false
): If true, JSNVL will not log any information about the validation process (such as when errors occur).
- ignoreExcessKeys (Boolean, Default
Schema Structure
Simple type checks:
let schema = {
name: "string",
age: "number",
sayName: "function",
}
let object = {
name: "Bob",
age: 15,
sayName: () => {}
}
JSNVL(object, schema) // true
In short, If a value in a schema is a string, JSNVL will check that the typeof
comparison counterpart is equal to that string.
An exception is that the string "object"
checks taht the typeof is an object AND the value is not null
.
Nullable type checks:
let schema = {
name: "?string",
}
let object = {
name: null,
}
JSNVL(object, schema) // true
Prefixing a type with ?
will allow that field to be nullable.
Inside Array
let schema = {
fruit: ["Banana","Plum"]
}
let object = {
fruit: "Plum"
}
JSNVL(object, schema) // true
If a value inside a schema is an array, JSNVL will check if the value in the object is inside that array.
Custom
let schema = {
oddNumber: (self) => self % 2 === 1
}
let object = {
oddNumber: 15
}
JSNVL(object, schema) // true
If a value inside a schema is a function, JSNVL will evaluate that function, passing the value of the object as the first parameter.
I encourage using self
for this name, and using currying to evaluate more complex functions.
A second parameter, parent
is also available, and will pass the object self
is enclosed in. This can be used for conditional evaluation,
such as:
let schema = {
start: "number",
end: (self, parent) => self > parent.start
}
let object = {
start: 10,
end: 15
}
JSNVL(object, schema) // true
object.end = 9;
JSNVL(object, schema) // false