bitschema
v1.1.0
Published
Simple schema validation for JavaScript
Downloads
1
Maintainers
Readme
BitSchema
BitSchema covers most validation and transformation requirements and also supports custom parsing for special cases.
Schema objects created with schema()
have a schema
property as well as parse
, parsePartial
, and parseProperty
methods. Each of these methods will always return either an object containing data
or invalid
.
Example:
import { schema } from "bitschema";
export const Book = schema({
title: "string|min:3",
pages: "number|optional",
});
Now this schema can be imported and used for data transformation and validation:
import { Book } from "/schema/Book.js";
const myBook = { title: "It", pages: 350 }
const { data, invalid } = Book.parse(ctx.payload);
Handling the returned data
or invalid
object
BitSchema will always return an object containing either a data
or invalid
object.
If validation passes, a data
object will be returned containing the parsed data which includes only properties defined
in the schema and transformed according to its data type. For example, if pages
is submitted as an input field in a
web form, this arrives at the server as a string type (because all values submitted through web forms are strings). But
because the specified type for pages
is "number"
, the returned value in data.pages
will be a number
type ready
for insertion to the database.
If validation fails, the invalid
object will contain the validation errors keyed by the field name. For example if
"abc" was submitted through a web form for pages
, the return value for invalid.pages
would be "Pages must be a
number"
.
Validating a partial object
In some cases, you may want to validate only a partial object. For example, when updating a record, you may want to
validate only the fields that were submitted. In this case, use the parsePartial()
method instead of parse()
like
this:
const { data, invalid } = Book.parsePartial(ctx.payload);
Note that only submitted fields will be validated and returned in the data
object. Any fields not submitted will be
ignored regardless whether specified as optional
or required (default).
Validating a single form field
You may also validate a single form field by passing in the property name and value to parseProperty
like this:
const { invalid, data } = Book.parseProperty("title", "Dune");
Schema types and options
A schema item must start with a data type followed by zero or more options. All types support optional
, default
,
label
, and custom functions. optional
makes the property optional.default
sets the default value (effectively
making it also optional). label
allows you to specify a custom label for the field name used in invalid
message
values and uses the key set to titlecase by default. For example, if the field name is title
, the default label will
be "Title". The label
option allows you to override this. For example, label:Book Title
will result in "Book Title"
being used in invalid
messages instead of "Title".
Available types and their respective options include:
"string"
Returns the parsed data
property as a string or returns an invalid
object.
min:<number>
: Minimum lengthmax:<number>
: Maximum lengthstartsWith:<string>
: Must start with specified stringendsWith:<string>
: Must end with specified stringincludes:<string>
: Must include specified stringemail
: Must match valid email formaturl
: Must match valid url formatid
: Must match valid MongoDB ObjectId formatoptional
: Field is optionaldefault
: Set a default string valuelabel
: A custom label for invalid messages<string>
: A custom function
"number"
Returns the parsed data
property as a number or returns an invalid
object.
min:<number>
: Minimum valuemax:<number>
: Maximum valueinteger
: Must be an integeroptional
: Field is optionaldefault
: Set a default number valuelabel
: A custom label for invalid messages<string>
: A custom function
"boolean"
Returns the parsed data
property as a number or returns an invalid
object. The following values are coerced to
true
: true
, "true"
, "1"
, 1
. The following values are coerced to false
: false
, "false"
, "0"
, 0
.
optional
: Field is optionaldefault
: Set a default boolean valuelabel
: A custom label for invalid messages<string>
: A custom function
object
Returns the object as is or returns an invalid
object. Note that this type is useful for validating objects of unknown
shape. If you know the shape of the object, it's better to use a nested object schema.
optional
: Field is optional- default is not supported for this type
label
: A custom label for invalid messages<string>
: A custom function
date
Returns the object as a date or returns an invalid
object.
optional
: Field is optional- default is not supported for this type
label
: A custom label for invalid messages<string>
: A custom function
any
Returns the value as is. Any value is accepted.
optional
: Field is optional- default is not supported for this type
label
: A custom label for invalid messages<string>
: A custom function
[string]
, [number]
, [boolean]
, [object]
, [date]
, [any]
These are the array equivalents of the above types. For example, [string]
will return an array of strings or an
invalid
object.
Custom functions
Any custom function can be used as a schema option in conjunction with a standard type. To do this, create a function
which receives the value and returns an object containing either data
or invalid
, then pass the function as a second
argument to the schema()
function. Then reference the function name as a schema option like this:
const { data, invalid } = schema({
pages: "number|isEven",
}, isEven);
function isEven(value) {
return value % 2 === 0
? { data: value }
: { invalid: "must be an even number" };
}
In line 2, we use the isEven
custom function as a schema option. Then in line 3, pass in the isEven
function defined
in line 5 which receives the value and returns either data
or invalid
depending on whether the value is divisible by
2. Note that the string assigned to invalid
will be prepended with the label
value, e.g., "Pages must be an even
number".