v1.11.0
Async custom validator supports
const schema = {
// Turn on async mode for this schema
$$async: true,
name: {
type: "string",
min: 4,
max: 25,
custom: async (v) => {
await new Promise(resolve => setTimeout(resolve, 1000));
return v.toUpperCase();
}
},
username: {
type: "custom",
custom: async (v) => {
// E.g. checking in the DB that whether is unique.
await new Promise(resolve => setTimeout(resolve, 1000));
return v.trim();
}
},
}
The compiled check
function has an async
property to detect this mode. If true
it returns a Promise
.
const check = v.compile(schema);
console.log("Is async?", check.async);
Meta-information for custom validators
You can pass any extra meta information for the custom validators which is available via context.meta
.
const schema = {
name: { type: "string", custom: (value, errors, schema, name, parent, context) => {
// Access to the meta
return context.meta.a;
} },
};
const check = v.compile(schema);
const res = check(obj, {
// Passes meta information
meta: { a: "from-meta" }
});