Overview
Akival encapsulates Yup for validation schemas and provides a simple API to build and validate data. Yup is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation.
Getting Started
Schema are comprised of parsing actions (transforms) as well as assertions (tests) about the input value. Validate an input value to parse it and run the configured set of assertions. Chain together methods to build a schema.
import { object, string, number, date, type InferType } from '@akinon/akival';
let userSchema = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date())
});
// parse and assert validity
const user = await userSchema.validate(await fetchUser());
type User = InferType<typeof userSchema>;
/* {
name: string;
age: number;
email?: string | undefined
website?: string | null | undefined
createdOn: Date
}*/Use a schema to coerce or “cast” an input value into the correct type, and optionally transform that value into more concrete and specific values, without making further assertions.
// Attempts to coerce values to the correct type
const parsedUser = userSchema.cast({
name: 'jimmy',
age: '24',
createdOn: '2014-09-23T19:25:25Z'
});
// ✅ { name: 'jimmy', age: 24, createdOn: Date }Know that your input value is already parsed? You can “strictly” validate an input, and avoid the overhead of running parsing logic.
// ❌ ValidationError "age is not a number"
const parsedUser = await userSchema.validate(
{
name: 'jimmy',
age: '24'
},
{ strict: true }
);Schema basics
Schema definitions, are comprised of parsing “transforms” which manipulate inputs into the desired shape and type, “tests”, which make assertions over parsed data. Schema also store a bunch of “metadata”, details about the schema itself, which can be used to improve error messages, build tools that dynamically consume schema, or serialize schema into another format.
In order to be maximally flexible yup allows running both parsing and assertions separately to match specific needs.
Parsing: Transforms
Each built-in type implements basic type parsing, which comes in handy when parsing serialized data, such as JSON. Additionally types implement type specific transforms that can be enabled.
const num = number().cast('1'); // 1
const obj = object({
firstName: string().lowercase().trim()
})
.json()
.camelCase()
.cast('{"first_name": "jAnE "}'); // { firstName: 'jane' }Custom transforms can be added
const reversedString = string()
.transform(currentValue => currentValue.split('').reverse().join(''))
.cast('dlrow olleh'); // "hello world"Transforms form a “pipeline”, where the value of a previous transform is piped
into the next one. When an input value is undefined yup will apply the schema
default if it’s configured.
Watch out! values are not guaranteed to be valid types in transform
functions. Previous transforms may have failed. For example a number transform
may receive the input value, NaN, or a number.
Validation: Tests
Akival schema run “tests” over input values. Tests assert that inputs conform to some criteria. Tests are distinct from transforms, in that they do not change or alter the input (or its type) and are usually reserved for checks that are hard, if not impossible, to represent in static types.
string()
.min(3, 'must be at least 3 characters long')
.email('must be a valid email')
.validate('no'); // ValidationErrorAs with transforms, tests can be customized on the fly
const jamesSchema = string().test(
'is-james',
d => `${d.path} is not James`,
value => value == null || value === 'James'
);
jamesSchema.validateSync('James'); // "James"
jamesSchema.validateSync('Jane'); // ValidationError "this is not James"Heads up: unlike transforms, value in a custom test is guaranteed to be
the correct type (in this case an optional string). It still may be
undefined or null depending on your schema in those cases, you may want to
return true for absent values unless your transform makes presence related
assertions. The test option skipAbsent will do this for you if set.
Customizing errors
In the simplest case a test function returns true or false depending on the
whether the check passed. In the case of a failing test, Akival will throw a
ValidationError with your (or the default) message for that test.
ValidationErrors also contain a bunch of other metadata about the test,
including it’s name, what arguments (if any) it was called with, and the path to
the failing field in the case of a nested validation.
Error messages can also be constructed on the fly to customize how the schema fails.
const order = object({
no: number().required().
sku: string().test({
name: 'is-sku',
skipAbsent: true,
test(value, ctx) {
if (!value.startsWith('s-')) {
return ctx.createError({ message: 'SKU missing correct prefix' })
}
if (!value.endsWith('-42a')) {
return ctx.createError({ message: 'SKU missing correct suffix' })
}
if (value.length < 10) {
return ctx.createError({ message: 'SKU is not the right length' })
}
return true
}
})
})
order.validate({ no: 1234, sku: 's-1a45-14a' })Composition and Reuse
Schema are immutable, each method call returns a new schema object. Reuse and pass them around without fear of mutating another instance.
const optionalString = string().optional();
const definedString = optionalString.defined();
const value = undefined;
optionalString.isValid(value); // true
definedString.isValid(value); // falseLocalization and i18n
The function setLocale can be used with your favorite i18n library.
import { setLocale } from '@akinon/akival';
import { i18n } from '@/i18n';
const { t } = i18n;
setLocale({
mixed: {
required: ({ path }) => t('field.is.a.required.field', { field: t(path) }) // "field.is.a.required.field" -> "{{field}} is a required field"
},
string: {
min: ({ path, min }) =>
t('field.must.be.at.least.min.characters', {
field: t(path),
min
}) // "field.must.be.at.least.min.characters" -> "{{field}} must be at least {{min}} characters"
}
});
let schema = akival.object().shape({
name: akival.string().min(2).required()
});
try {
await schema.validate({ name: 'jimmy' });
} catch (err) {
console.log(err);
}