Gathering detailed insights and metrics for schema-to-yup
Gathering detailed insights and metrics for schema-to-yup
Gathering detailed insights and metrics for schema-to-yup
Gathering detailed insights and metrics for schema-to-yup
npm install schema-to-yup
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
284 Stars
366 Commits
51 Forks
9 Watching
26 Branches
16 Contributors
Updated on 13 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-0.5%
11,538
Compared to previous day
Last week
-0.2%
70,772
Compared to previous week
Last month
19%
298,104
Compared to previous month
Last year
364.2%
2,454,331
Compared to previous year
4
5
Build a Yup schema from a JSON Schema, GraphQL schema (type definition) or any other similar type/class and field/properties model or schema :)
See Advanced config for all the more advanced configuration options available to customize this builder to support any of your requirements.
The builder currently supports the most commonly used JSON Schema layout
To support other schemas see Advanced config
You can use the YupBuilderConfig
and TypeHandlerConfig
type interfaces to facilitate building up the config
object to pass to the YupBuilder
.
Install
npm install schema-to-yup -S
or yarn add schema-to-yup
Create a JSON schema to validate against
1const schema = { 2 $schema: "http://json-schema.org/draft-07/schema#", 3 $id: "http://example.com/person.schema.json", 4 title: "Person", 5 description: "A person", 6 type: "object", 7 properties: { 8 name: { 9 description: "Name of the person", 10 type: "string", 11 }, 12 email: { 13 type: "string", 14 format: "email", 15 }, 16 foobar: { 17 type: "string", 18 matches: "(foo|bar)", 19 }, 20 age: { 21 description: "Age of person", 22 type: "number", 23 exclusiveMinimum: 0, 24 required: true, 25 }, 26 characterType: { 27 enum: ["good", "bad"], 28 enum_titles: ["Good", "Bad"], 29 type: "string", 30 title: "Type of people", 31 propertyOrder: 3, 32 }, 33 }, 34 required: ["name", "email"], 35};
Create a config
object to configure details of your validation
1const config = { 2 // for error messages... 3 errMessages: { 4 age: { 5 required: "A person must have an age", 6 }, 7 email: { 8 required: "You must enter an email address", 9 format: "Not a valid email address", 10 }, 11 }, 12};
Create the yup schema using the builder method buildYup
1const { buildYup } = require("schema-to-yup"); 2const yupSchema = buildYup(schema, config);
Use the yup schema methods such as isValid
to validate
1// console.dir(schema) 2const valid = await yupSchema.isValid({ 3 name: "jimmy", 4 age: 24, 5}); 6 7console.log({ 8 valid, 9}); 10// => {valid: true}
The above example would generate the following sort of Yup validation schema:
1const schema = yup.object().shape({ 2 name: yup.string().required(), 3 age: yup.number().required().positive(), 4 // ... 5});
Please note that this library does not currently resolve $ref
(JSON Pointers) out of the box. You can use another library for that.
You could f.ex use json-schema-ref-parser to preprocess your schema. Also see:
By default, any property will be explicitly notRequired
unless set to be required, either via required: true
in the property constraint object or via the required
list of properties of the object
schema definition (of the property).
You can override the notRequired
behavior by setting it on the new mode
object of the configuration which can be used to control and fine-tune runtime behaviour.
1const jsonSchema = { 2 title: "users", 3 type: "object", 4 properties: { 5 username: { type: "string" }, 6 }, 7};
1const yupSchema = buildYup(jsonSchema, {
2 mode: {
3 notRequired: true, // default setting
4 },
5});
6
7// will be valid since username is not required by default
8const valid = yupSchema.validateSync({
9 foo: "dfds",
10});
1const yupSchema = buildYup(jsonSchema, {
2 mode: {
3 notRequired: true, // default setting
4 },
5});
6// will be invalid since username is required by default when notRequired mode is disabled
7const valid = yupSchema.validateSync({
8 foo: "dfds",
9});
The new run time mode settings are demonstrated under sample-runs/mode
No validation error (prop not required unless explicitly specified):
$ npx babel-node sample-runs/modes/not-required-on.js
Validation error if not valid type:
$ npx babel-node sample-runs/modes/not-required-on.js
You can access the internal Yup shape, via shapeConfig
on the yup schema returned by the buildYup
schema builder function. Alternatively simply call propsToShape()
on the yup builder.
This allows you to easily mix and match to suit more advanced requirements.
1const { buildYup } = require("json-schema-to-yup"); 2const { shapeConfig } = buildYup(json, config); 3// alternatively 4// const shape = buildYup(json, config).propsToShape() 5const schema = yup.object().shape({ 6 ...shapeConfig, 7 ...customShapeConfig, 8});
Currently the following schema types are supported:
array
boolean
date
number
object
string
strict
default
nullable
const
required
notRequired
oneOf
(enum
, anyOf
)notOneOf
refValueFor
for confirm password scenariotypeError
custom type error message (in config)when
isType
nullable
(isNullable
)Reference constraints within the schema can be defined as follows:
1schema = { 2 required: ["startDate", "endDate"], 3 type: "object", 4 properties: { 5 startDate: { 6 type: "number", 7 }, 8 endDate: { 9 type: "number", 10 min: "startDate", 11 }, 12 }, 13};
Internally this will be resolved using Yup.ref
as documented here in the Yup readme.
ref
allows you to reference the value of a sibling (or sibling descendant) field to validate the current field.
Yup.ref
is supported in the Yup docs for the following:
ensure
compact
items
(of
)maxItems
(max
)minItems
(min
)itemsOf
(of
)No keys
maxDate
(max
)minDate
(min
)integer
moreThan
(exclusiveMinimum
)lessThan
(exclusiveMaximum
)positive
negative
min
(minimum
)max
(maximum
)truncate
round
camelCase
constantCase
noUnknown
(propertyNames
)minLength
(min
)maxLength
(max
)pattern
(matches
or regex
)email
(format: 'email'
)url
(format: 'url'
)lowercase
uppercase
trim
For pattern (RegExp) you can additionally provide a flags property, such as flags: 'i'
. This will be converted to a RegExp
using new RegExp(pattern, flags)
For the pattern
constraint you can also pass in excludeEmptyString
to exclude empty string from being evaluated as a pattern constraints.
The library JSON Schema model builder is a powerful toolset to build a framework to create any kind of output model from a JSON schema.
If you enjoy this declarative/generator approach, try it out!
See Advanced config
Uses jest for unit testing.
NumericConstraint
)A new version is under development at schema-to-yup-mono which is this code ported to a lerna monorepo with a cleaner, mode modular structure. More work needs to be done in terms of TDD and unit testing. Ideally this repo should be ported to Nx
Please feel free to come with ideas and suggestions on how to further improve this library.
2018 Kristian Mandrup (CTO@Tecla5)
No vulnerabilities found.
No security vulnerabilities found.