Getting started
How does Validatem work?
Validatem is a little different from most other validation libraries. In those, you often need to either chain a lot of method calls, or specify a bunch of strings to define the validation rules. But those approaches have a big limitation: you're pretty much expected to use the validators that come with the library, and adding your own more precise validation rules is a hassle. So in practice, you usually won't bother, and you end up with very inconsistent validation.
This also happens in other ways; the library itself is usually designed very monolithically. It expects you to use it in a particular way, for a particular purpose, and anything else is painful to do. A form validation library only validates form input. A configuration file validator only validates configuration files. A CLI argument validator only validates CLI arguments. And so on. And each of these have a completely different syntax, and a different set of validation rules they can apply.
Validatem, instead, uses regular functions as its validators. There is nothing special about these - an 'official' validator works the exact same way as one from a third-party package, or one in your own code. They're all equally easy to use. I think this is important, because it encourages people to share their work and collaborate on a much bigger commons of off-the-shelf validators, instead of being limited to what the maintainers of a library thought to put into it. Of course you need to actually find these validators, and so you can find a categorized index here.
Validatem makes very few assumptions about how you use it, too; it provides a basic set of validation functions, that all take the same kind of validation schema and produce structured validation errors. You can integrate it into whatever you need it for, whether that's validating form data, configuration files, or something completely different. And the core is small enough that you can totally use it in a library to validate function arguments!
Okay, so how do I use it?
For most cases, you'll end up using one of these functions, all of them exported from @validatem/core:
validateArguments(arguments, schema): Validates the arguments to a function call against the specified schema, and throws a descriptive AggregateValidationError if any of the arguments are invalid.validateOptions(arguments, schema): A variant ofvalidateArgumentsfor functions that only take an options object (ie. that only have named arguments). The schema is applied to that object, instead of all of the arguments.validateValue(value, schema): Validates an arbitrary value against the specified schema, and throws an AggregateValidationError if it fails. This is also used for most custom integrations.testValue(value, schema): LikevalidateValue, but returnstrueif validation succeeded orfalseif not, and never throws an error. It doesn't tell you what's wrong, and so it's mostly useful for testing individual validators against a value, eg. in conditionals. But it will accept all the same schemas as everything else.
The "schema" here is simply a validator, and that validator can either implement a single rule or combine multiple other rules, making it a "combinator". For example, the following are some examples of valid schemas:
1
2
3
isString
arrayOf(isBoolean)
{ oneProperty: [ required, isString ], anotherProperty: isNumber }
When you use an object literal in a schema directly, it is automatically converted to a hasShape validator internally; this is what you would typically use to validate a nested object structure. When you use an array literal in a schema directly, it simply means that multiple validators are applied in sequence - [ isString ] and isString mean exactly the same thing.
Here is an example of what a real-world validation schema might look like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const { validateArguments } = require("@validatem/core");
const required = require("@validatem/required");
const defaultTo = require("@validatem/default-to");
const isString = require("@validatem/is-string");
const isBoolean = require("@validatem/is-boolean");
const isInteger = require("@validatem/is-integer");
let validatedArguments = validateArguments(arguments, {
/* Yes, these arguments are positional, even though we're using object syntax; this works because objects in JS are ordered! */
name: [ required, isString ],
properties: [ required, {
activated: [ required, isBoolean ],
suspended: [ defaultTo(false), isBoolean ],
infractions: isInteger
}]
});
In this example, we're validating arguments to a function call. The first argument is a required name argument, which must be a string; the second argument is an object containing a number of different properties, one of which is also required to be specified, and one of which has a default value specified.
Look closely at how for the properties argument, the schema contains an object literal and a required validator. By default, validators in Validatem - including combinators like hasShape! - allow undefined and null values, and those will skip all the validators entirely, since it doesn't make sense to validate a value that isn't there.
To disallow that for any given value, whether it's a function argument or an object property or anything else, you specify the required validator, which will fail if it encounters a null or undefined. You can also choose to use defaultTo to specify a default value for that case.
As validation libraries go, Validatem is a little different. For example, unlike Joi (where every validator is a chained method) or checkit (where every validator is a string name), a validator in Validatem is just a function that receives the to-be-validated value as an argument. That function can do a few different things:
- Return with nothing: Consider the value valid, and don't transform it.
- Return with a new value: Consider the value valid, but transform it to something else (eg. a parsed version).
- Throw or return a ValidationError: Consider the value invalid; the message of the error is what shows up in the validation results.
- Throw with a different kind of error: Indicate that something is wrong (eg. there is a bug in the code); this error will be passed through as-is, and validation will be aborted.
- Return a validationResult object: This can be done to return multiple errors, or a combination of errors and a new value. Unless you're writing a combinator, you probably don't need this.
Importantly, you can write these functions yourself, and custom validators - whether written by you or by someone else - are on equal footing with the 'official' validators. They are just as easy to use, and just as easy to combine. In fact, all of the official validators are packaged as if they were third-party packages!
Validating a value or a function's arguments, then, is just a matter of calling one of the validation functions with the desired validation schema. Either it will pass (and return the validated value, optionally transformed), or it will fail and throw an AggregrateValidationError with a clear description of what's wrong:
TODO: Insert error example here
There are a number of different validation functions included in @validatem/core:
- validateArguments: This validates a function's arguments against a validation schema. The schema describes the complete set of arguments, and the validation rules for each of them.
- validateOptions: Like
validateArguments, but specifically for functions which only take a singleoptionsargument. You can directly specify the allowable options as the schema. Note that this does not work for React components; seevalidate-propsbelow. - validateValue: This validates an arbitrary value against a validation schema. The schema is directly applied to the value.
- testValue: Like
validateValue, but instead of throwing an error, it returns a boolean that indicates whether the value matched the schema. This should not be used for actual validation; it's meant to be used for cases like "this function allows a few different kinds of input, and I need to execute different logic for each". You'd then usetestValueto reuse the same validators in your conditional logic.
Additionally, some more validation utility functions are available as separate packages:
- validate-form: This validates incoming form data, and specially formats error metadata so that it's easy to eg. highlight the failing fields.
- validate-props: This validates the props for a functional React component. Because those components actually receive more than one argument, even if you usually only interact with the first one, the usual
validateOptionsdoesn't work here.
Transforming values
TODO: explain why defaultTo etc. are useful, self-documenting
Combining (composing) validators
TODO: show array syntax TODO: show why wrapError can be useful
TODO: explain how linters can interfere?
TODO: explain how either can be used like a match statement, like is done in raqb with wrapping