Coder Social home page Coder Social logo

schema-to-yup's Introduction

Schema to Yup schema

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.

JSON schema

The builder currently supports the most commonly used JSON Schema layout

To support other schemas see Advanced config

Typescript and Typings

You can use the YupBuilderConfig and TypeHandlerConfig type interfaces to facilitate building up the config object to pass to the YupBuilder.

Quick start

Install

npm install schema-to-yup -S or yarn add schema-to-yup

Create a JSON schema to validate against

const schema = {
  $schema: "http://json-schema.org/draft-07/schema#",
  $id: "http://example.com/person.schema.json",
  title: "Person",
  description: "A person",
  type: "object",
  properties: {
    name: {
      description: "Name of the person",
      type: "string",
    },
    email: {
      type: "string",
      format: "email",
    },
    foobar: {
      type: "string",
      matches: "(foo|bar)",
    },
    age: {
      description: "Age of person",
      type: "number",
      exclusiveMinimum: 0,
      required: true,
    },
    characterType: {
      enum: ["good", "bad"],
      enum_titles: ["Good", "Bad"],
      type: "string",
      title: "Type of people",
      propertyOrder: 3,
    },
  },
  required: ["name", "email"],
};

Create a config object to configure details of your validation

const config = {
  // for error messages...
  errMessages: {
    age: {
      required: "A person must have an age",
    },
    email: {
      required: "You must enter an email address",
      format: "Not a valid email address",
    },
  },
};

Create the yup schema using the builder method buildYup

const { buildYup } = require("schema-to-yup");
const yupSchema = buildYup(schema, config);

Use the yup schema methods such as isValid to validate

// console.dir(schema)
const valid = await yupSchema.isValid({
  name: "jimmy",
  age: 24,
});

console.log({
  valid,
});
// => {valid: true}

The above example would generate the following sort of Yup validation schema:

const schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive(),
  // ...
});

Refs

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:

Mode

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.

const jsonSchema = {
  title: "users",
  type: "object",
  properties: {
    username: { type: "string" },
  },
};
const yupSchema = buildYup(jsonSchema, {
  mode: {
    notRequired: true, // default setting
  },
});

// will be valid since username is not required by default
const valid = yupSchema.validateSync({
  foo: "dfds",
});
const yupSchema = buildYup(jsonSchema, {
  mode: {
    notRequired: true, // default setting
  },
});
// will be invalid since username is required by default when notRequired mode is disabled
const valid = yupSchema.validateSync({
  foo: "dfds",
});

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

Shape

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.

const { buildYup } = require("json-schema-to-yup");
const { shapeConfig } = buildYup(json, config);
// alternatively
// const shape = buildYup(json, config).propsToShape()
const schema = yup.object().shape({
  ...shapeConfig,
  ...customShapeConfig,
});

Types

Currently the following schema types are supported:

  • array
  • boolean
  • date
  • number
  • object
  • string

Mixed (any type)

  • strict
  • default
  • nullable
  • const
  • required
  • notRequired
  • oneOf (enum, anyOf)
  • notOneOf
  • refValueFor for confirm password scenario
  • typeError custom type error message (in config)
  • when
  • isType
  • nullable (isNullable)

Reference constraints

Reference constraints within the schema can be defined as follows:

schema = {
  required: ["startDate", "endDate"],
  type: "object",
  properties: {
    startDate: {
      type: "number",
    },
    endDate: {
      type: "number",
      min: "startDate",
    },
  },
};

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:

Array

  • ensure
  • compact
  • items (of)
  • maxItems (max)
  • minItems (min)
  • itemsOf (of)

Boolean

No keys

Date

  • maxDate (max)
  • minDate (min)

Number

  • integer
  • moreThan (exclusiveMinimum)
  • lessThan (exclusiveMaximum)
  • positive
  • negative
  • min (minimum)
  • max (maximum)
  • truncate
  • round

Object

  • camelCase
  • constantCase
  • noUnknown (propertyNames)

String

  • 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.

Similar projects

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!

Advanced config

See Advanced config

Testing

Uses jest for unit testing.

  • Have unit tests that cover most of the constraints supported.
  • Could use some refactoring using the latest infrastructure (see NumericConstraint)
  • Please help add more test coverage and help refactor to make this lib even more awesome :)

Development

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

Ideas and suggestions

Please feel free to come with ideas and suggestions on how to further improve this library.

Author

2018 Kristian Mandrup (CTO@Tecla5)

schema-to-yup's People

Contributors

andresouza avatar benoit-nadaud avatar buildxyz-git avatar dependabot[bot] avatar designbyonyx avatar ecnaidar avatar jamaybyrone avatar kristianmandrup avatar lookfirst avatar matthewfaircliff avatar mrloh avatar npup avatar ritchieanesco avatar shahzaib-deriv avatar syastrebov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schema-to-yup's Issues

Can't get type="string" format="email" to work

Hi,

I can't seem to get type="string", format="email" to do validation on email format.
I have a simple JSON schema with just 1 email field:

import { buildYup } from "json-schema-to-yup";

let test2JSON:any={

  "title": "Company Edit",
  "type": "object",
  "additionalProperties": false,
  "description": "A record",
  "properties": {
    "testemail": {
      "type": "string",
      "format": "email",
      "description": "Test Email",
      "title": "Email",
      "minLength": 10
    }
  }
}

let validateSchema = buildYup(test2JSON);
console.log(validateSchema);

When examining the validateSchema (ObjectSchema) returned, I see under fields.testemail.tests , is an array with just one entry for "min" testing (${path} must be at least ${min} characters) with the correct params for min testing {min:10}. There is no email format testing at all.

What am I doing wrong? Thanks in advance!

[ Note: I am using latest json-schema-to-yup, .. the schema-to-yup doesn't seem to work with 'required'. Both are not responding to type="string" , format="email" anyway. ]

Question: Yup to jsonschema

Hey Kristian,

Congrats on the great idea and project! I'm opening this issue because I'm also interested in doing the opposite, which is transforming a yup schema into a jsonschema. Do you think that would make sense and be possible to do so with schema-to-yup? Do you know any other projects that do that?

Is possible to do custom format validations?

Is possible to add custom "format" validations? Let me explain with a practical example:
I need to validate a text field that stores a document (CPF [Brazil]) number that follows math. logic. Considering this, I can code the logic via schema-to-yup?

OBS: I think that it can be solved implementing a Custom constraint handler functions, but I did not understand it so well :/

Thanks in advance 😄

Custom type error message

Hi I would like to know if there's a way to implement or a idea to make able to custom the errors based on types.

Per example this:

decimal_places must be a `number` type, but the final value was: `NaN` (cast from the value `NaN`).

would be I guess a way to pass to errMessages a property called 'type' where you can customize this error.

I have read this ticket #36 but I think it is not being solved, since there's no way to define a generic error for type mismatches

Thanks!

[Question] - Function for custom validation

Hi,

Is there any way to create a custom validation function?

I have the yup schema below:

const userSchema = yup.object().shape({    
        name: yup.string().required(),    
        id: idValidation().required(),    
        phone: yup.string()    
    });

I want to create this same schema with json schema.

It is possible?

Thanks.

Rafael.

When Constraint Errors

Not sure if I am building wrong but using the example from the readme docs I can't get the following to build with buildYup.

const biggyJson = {
  title: "biggy",
  type: "object",
  properties: {
    isBig: {
      type: "boolean"
    },
    count: {
      type: "number",
      when: {
        isBig: {
          is: true,
          then: {
            min: 5
          }
        }
      }
    }
  }
};

I get the following error:

> build = buildYup(biggyJson)
Thrown:
TypeError: ref must be a string, got: [object Object]
    at new Reference (C:\...\node_modules\schema-to-yup\node_modules\yup\lib\Reference.js:25:40)
    at C:\...\node_modules\schema-to-yup\node_modules\yup\lib\mixed.js:433:14
    at Array.map (<anonymous>)
    at NumberSchema.when (C:\...\node_modules\schema-to-yup\node_modules\yup\lib\mixed.js:432:32)
    at e.multiValueConstraint (C:\...\node_modules\schema-to-yup\dist\index.js:1:8745)
    at e.build (C:\...\node_modules\schema-to-yup\dist\index.js:1:7977)
    at e.addConstraint (C:\...\node_modules\schema-to-yup\dist\index.js:1:9201)
    at e.n.addConstraint (C:\...\node_modules\schema-to-yup\dist\index.js:1:14541)
    at e.n.when (C:\...\node_modules\schema-to-yup\dist\index.js:1:16025)

Compiled version of this lib

I’m building a project to auto generate cm/s forms from GraphQL Schemas, wanted to use Formik and than cake across this package and graphSchemaToJson. I have a basic form generator build and decided to rewrite graphSchemaToJson because I encountered too many issues with that library and didn’t like the design. I’m rewriting it to return actual JSON Schema, like this library expects normally. Once this is ready I can let you know, maybe it’s interesting for this lib too.

I haven’t dug very deep into this library yet but it seems much better build. However I need a browser version, so not having a compiled package makes this unusable for me.

Are you planing to provide a proper compiled version or what you accept a PR that provides a compiled version using microbundle. Otherwise I’d just fork the code from this lib into mine and provide a new package.

Enum

Hello @kristianmandrup I am trying to get a json schema with enum to work and it does not seem to get picked up. Am I doing something wrong? Is this a feature that is coming in a future version? Can I help in any way?

const json = {
  definitions: {},
  $schema: 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  title: 'Entry Submit Schema',
  required: ['email'],
  additionalProperties: false,
  properties: {
    email: {
      type: 'string',
      pattern: '^\\b[\\w\\.-]+@[\\w\\.-]+\\.\\w{2,4}\\b$',
      enum: ['[email protected]'],
      description: 'Email Address',
    },
  },
};

does not produce any tests to make sure the email is [email protected] for an example.

Would love to use this fantastic library and willing to help in any way I can.

toEntry: unknown type date

This looks really promising and we are looking to use it in our project! The only thing is it doesn't seem like the date validator is working?

Minimal repro steps:

buildYup({
  type: 'object',
  properties: {
    date: {
      type: 'date',
      minDate: new Date()
    }
  },
});

It says the following error: toEntry: unknown type date

Here is the output from the above call:
image

I couldn't work out if I was doing anything wrong but according to the docs it looks fine. Strings work as expected.

support for nested objects and arrays

I realized that neither nested objects, nor checking for types inside arrays are working yet (I could see that latter has simply not been implemented yet). I'd be happy to try to help out here, but I know you are in the middle of a typescript rewrite, so what's the best way to contribute, would you merge features back into master?

Here is an example json-schema that fails. Both the nested topFeature object and features array doesn't get any tests attached.

"{
  "title": "FeatureCardSection",
  "type": "object",
  "properties": {
    "features": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "title": { "type": "string" },
          "description": { "type": "string" }
        },
        "required": ["title"]
      }
    },
    "topFeature": {
      "type": "object",
      "properties": {
        "title": { "type": "string" },
        "description": { "type": "string" }
      },
      "required": ["title"]
    }
  },
  "required": ["features"]
}"

Bug: Config is not defined

In version 1.9.23, I tried to run the base example included in README.md but it throwing an error: ReferenceError: config is not defined

Uncaught ReferenceError: config is not defined
at e.initResolvers (property-value-resolver.js:13)
at new e (property-value-resolver.js:8)
at $ (property-value-resolver.js:3)
at e.createPropertyValueHandler (entry.js:48)
at e.setPropertyHandler (entry.js:33)
at new e (entry.js:25)
at Object.J [as createYupSchemaEntry] (create-entry.js:3)
at e.createYupSchemaEntry (index.js:153)
at e.propToYupSchemaEntry (index.js:143)
at index.js:130
at Array.reduce ()
at e.objPropsToShape (index.js:127)
at e.propsToShape (index.js:114)
at new e (index.js:44)
at Z (index.js:15)

Error when "type" is array

Hello,

Following the spec ,
the "type" property can be string or array.
However, when I used the schema below for "buildYup", an error would be happened.

const schema = {
  $schema: "http://json-schema.org/draft-07/schema#",
  $id: "http://example.com/person.schema.json",
  title: "Person",
  description: "A person",
  type: "object",
  properties: {
    name: {
      description: "Name of the person",
      type: ["string", 'null']
    },
    email: {
      type: "string",
      format: "email"
    },
    
  },
  required: ["name", "email"]
};

image

I also checked the schema via https://www.jsonschemavalidator.net/, and it ok with draft v7.
image

Please help to check, @kristianmandrup

Thanks.

Nested required fields not throwing error

Let's say I have the following JSON schema:

const { buildYup } = require("json-schema-to-yup");
const schema = {
  $schema: "https://json-schema.org/draft/2019-09/meta/core",
  $id: "url",
  title: "title",
  description: "description",
  type: "object",
  properties: {
    first_name: {
      description: "Your first name",
      type: "string",
      component: "TextInput"
    },
    last_name: {
      description: "Your last name",
      type: "string",
      component: "TextInput"
    },
    extra: {
      description: "Extra data",
      type: "object",
      properties: {
        age: {
          description: "Your age",
          type: "number",
          component: "TextInput"
        }
      },
      required: ["age"]
    }
  },
  required: ["first_name", "last_name"]
}


const yupSchema = buildYup(schema);
const person = { first_name: 'jimmy' }

yupSchema.validate(person, { abortEarly: false }).catch(function(err) {
  err.inner.map((e) => console.log(e.path, e.message))
});

Returns:

last_name last_name is a required field

And: person = { first_name: 'jimmy', last_name: "Doe" } returns no errors.

Expected

I would expect the validation to fail and throw an error saying the age field is required.

Update

I just noticed this closed issue, but I guess it's not working/merged? Or at least the required field.

Another example

{ 
   type:"object",
   required:[ 
      "name",
      "age",
      "club_name"
   ],
   properties:{ 
      name:{ 
         type:"object",
         required:[ 
            "first_name",
            "last_name"
         ],
         properties:{ 
            first_name:{ 
               type:"string"
            },
            last_name:{ 
               type:"string"
            }
         }
      },
      age:{ 
         type:"integer"
      },
      club_name:{ 
         type:"string"
      }
   }
}

const yupSchema = buildYup(schema);
const person = {}

yupSchema.validate(person, { abortEarly: false }).catch(function(err) {
  err.inner.map((e) => console.log(e.path, e.message))
});

Returns

club_name club_name is a required field
age age is a required field

No errors about the name property.

Failed unit tests

@kristianmandrup just checked out the latest commit and can see a few failed test.

test/types/object/complex-schema.test.js
complex nested object schema › invalid json › is invalid

test/conditions/when-then-condition.test.js
WhenCondition › use WhenCondition › validate

test/types/string/enum.test.js
enum › encountered a declaration exception

test/types/string/oneOf.test.js
oneOf › schema opts › negative - ok

test/types/string/notOneOf.test.js
notOneOf › validate › encountered a declaration exception

test/schema-when-then.test.js
when › isBig › encountered a declaration exception

test/schema-when-then-otherwise.test.js
when › then otherwise › encountered a declaration exception

test/convert.test.js
converts JSON schema to Yup Schema and validates

test/types/object/complex-schema.test.js
complex nested object schema › invalid json › is invalid

A lot of these refer to constraintFn... i'll have a go at fixing them but might take some time for me to get my head around it

Is this library stable?

Hi,

i am checking out your library but I am not sure if it is stable. Many tests fail and also some of the examples on the README do not produce correct yup schemas.

e.g.

age: {
  type: "number",
  min: 0,
  max: 20
}

The value in the yup tests is undefined.

So I wanted to ask, if I am doing something wrong or if the library is just experimental. Because it seems quite mature and would be very useful.

Required Fields are not returning Error Messages

Description
Using the validateSync method to validate a required field. We expected an custom error message to be returned instead received a boolean

  const schema = {
    title: "users",
    type: "object",
    required: ["username"],
    properties: {
      username: {
        type: "string"
      }
    }
  };

  const config = {
    errMessages: {
      username: {
        required: "User is required"
      }
    }
  };
  const yupSchema = buildYup(schema, config);
  const valid = yupSchema.validateSync({  }); //expect to return error message

Expected
A custom error message

Actual
A boolean was returned

1.9.13 breaks required

On 1.9.11, this works as expected:

const { buildYup } = require("schema-to-yup");
const jsonSchema = {
  title: "users",
  type: "object",
  required: ["username"],
  properties: {
    username: { type: "string" , required: true }
  }
};
const yupSchema = buildYup(jsonSchema, {
  mode: {
    notRequired: true
  },
});
try {
  const valid = yupSchema.validateSync({
    foo: "dfds"
  });
  console.log(valid); // this should not happen
} catch(e) {
  console.log(e); // this should happen
}

and throws an error. It works with only either required: true or required: ["username"]. (Just noticed that using only notRequired: true does not work although it should if I'm understanding the documentation correctly?)

However, on 1.9.13 (latest) none of those settings work, the validation never throws even if all three are on. On freshly checked out and built copy of the master branch, required: true and required:["username"] work but notRequired: true does not.

A new release might be in order?

create index.d.ts

fails:

dts-gen -m json-schema-to-yup

TypeError: Cannot read property 'isInteger' of undefined

Matches/RegExp doesn't allow for flags

It seems like there is currently no way to define the optional flags for a RegExp, example: i for case-insensitive matches.

It is possible to work around this by modifying the regexp to explicitly capture both lowercase/uppercase characters, but this can be tedious for complex expressions.

Extended email validation

Hello! How could I exclude cyrillic symbols from string?

My code:
"properties": { "email": { "type": "string", "title": "", "description": "", "format": "email", "meta": { "component": "InputMaskField" }, "maxLength": 60 } },

I want to exclude cyrillic and maybe some other symbols. 'matches' is not working.

Yup custom error messages not working as expected

FAIL test/messages.test.js

yup inserts custom messages for required fields

expect(received).toBe(expected) // Object.is equality

Expected: "User is required"
Received: true

  27 |     valid = e.errors[0];
  28 |   }
> 29 |   expect(valid).toBe("User is required");
     |                 ^
  30 | });
  31 | test("yup inserts custom messages for regex fields", () => {
  32 |   const message2 = {

  at Object.toBe (test/messages.test.js:29:17)

cant read multiple types in an array and cant have a property named "type"

schema-to-yup - v 1.9.14
yup - 0.27.0

I have a json schema with properties of type ["string, "null"] but it cant read this properly. How do I go about adding my own custom type handler for this?

I also have a property called "type" which it tries to use as the property's type. Is there a way of getting around this too?

thanks

When Then Otherwise Tests are failing

@kristianmandrup

looking at fixing these tests. I'm just looking through the code and found this:

//src/conditions/when/when-entry.js

  calcEntryObj() {
    // clone
    let whenEntryObj = {
      ...this.whenEntryObj
    };

    // const { is } = whenEntryObj;
    // const checkedIs = this.checkIs(is);
    // if (!checkedIs) {
    //   this.warn(`calcEntryObj: missing or invalid is constraint`, is);
    //   return whenEntryObj;
    // }
    const otherwiseKey = whenEntryObj.then ? "else" : "otherwise";

    whenEntryObj = this.whenEntryFor(whenEntryObj, "then");
    whenEntryObj = this.whenEntryFor(whenEntryObj, "otherwise", otherwiseKey);
    return whenEntryObj;
  }

I'm not too sure what you are trying to do prior to returning the when object as you seem to override the previous whenEntryObj. Any clarification would be awesome.

Min does not work

Hi,

Hm-m.. Somehow this config
{ type: "number", integer: true, min: 0 }

does not work. It validates numbers like '-5' etc. I am using version 1.9.1 of the lib.

Am I doing it wrong? Please, suggest. Thanks!

Required tag wrongly assigned to property

Hi there,

I'm facing this issue where when I buildYup, it is changing the schema to make a field required which is not meant to be according to the schema.
Here is a small jest test demonstrating the issue.

it('should maintain the same schema after buildYup', () => {
  const basicSchema = {
    $schema: 'http://json-schema.org/draft-04/schema#',
    description: 'Test',
    properties: {
      id: {
        $ref: '#/definitions/uuid',
      },
      customer_id: {
        $ref: '#/definitions/uuid',
      },
    },
    title: 'Test',
    required: [
      'id',
    ],
    additionalProperties: false,
    definitions: {
      uuid: {
        pattern: '[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$',
        type: 'string',
      },
    },
  };
  const jsonSchema = deref(basicSchema);
  jsonSchema.type = 'object';
  const jsonSchemaBefore = cloneDeep(jsonSchema);
  buildYup(jsonSchema, {});
  expect(jsonSchemaBefore).toEqual(jsonSchema); <--- This fails when I expect it to pass
});

By calling buildYup the schema is changing to force both id and customer_id to be required even though only id should be required by the schema. Any ideas why this is?

oneOf and maxLength errors

Hi,

I'm trying to use your plugin but if schema contains select (enum's) or textarea (with maxLength) it's doesn't work - error message appears.

Here is part of schema in properties:

"peopleType": {
                "enum": [
                    "good",
                    "bad",
                ],
                "enum_titles": [
                    "Good",
                    "Bad",
                ],
                "type": "string",
                "title": "Type of people",
                "propertyOrder": 4
            },

and it throws:

TypeError: Cannot read property 'oneOf' of undefined
YupString.oneOf
node_modules/json-schema-to-yup/src/types/mixed.js:61

Same thing if I have textarea (type string) with maxLength: 2000 and it throws:

TypeError: Cannot read property 'maxLength' of undefined
YupString.maxLength
node_modules/json-schema-to-yup/src/types/string.js:68

Why is that?

Unable to read `$ref` in a schema

I have a example schema as below:

I have 2 schemas

root.json
common.json

I am using root to convert to yup, in root is a reference to common

 "userName": {"$ref": "common.json#/definitions/user-name" },

I get an uncaught error, unless I add a type, but I realize it's not getting the pattern from the common definition at all.

What am I doing wrong?

Bug: array fields do not work

Hey, great tool - much appreciated. Started using it on a project and I was getting an error on array fields, even really simple ones:

buildYup({
  type: 'object',
  properties: {
    foo: {
      type: 'array',
      items: {
        type: 'string'
      }
    }
  }
})

>> [itemsOf: Error] TypeError: `array.of()` sub-schema must be a valid yup schema, or `false` to negate a current sub-schema. not: { ... }

I dug through the code and discovered that the "items" schema was not getting passed to the underlying yup constraint function. I'm about to open a PR which fixes the issue (along with tests).

package is not working properly

Hi guys, I installed this package but seems that almost nothing is working properly:

  • Yup version: 0.27.0
  • schema-to-yup version: 1.9.19

For the schema below, required are not working, password minLength and maxLength don't work either. Actually I think that the only thing is working is the email format.

{ 
   "$schema":"http://json-schema.org/draft-07/schema#",
   "$id":"http://example.com/person.schema.json",
   "type":"object",
   "properties":{ 
      "email":{ 
         "type":"string",
         "format":"email",
         "maxLength":100,
         "required":true
      },
      "password":{ 
         "type":"string",
         "minLength":3,
         "maxLength":20,
         "required":true
      }
   },
   "required":[ 
      "email",
      "password"
   ]
}

Email Format property not returning customer error message

Description
JSON schema specification provides the "format" property. I am using this property to validate a email field. However the returned value is not a custom error message but a boolean.

let valid;
let message = {
  title: "email",
  type: "object",
  required: ["email"],
  properties: {
    email: {
      type: "string",
      format: "email"
    }
  }
};
let config = {
  errMessages: {
    email: {
      format: "Email format incorrect"
    }
  }
};

// this test fails as it returns a boolean
it("yup inserts custom messages for format", () => {
  try {
    const yupSchema = buildYup(message, config); 
    valid = yupSchema.validateSync({ email: "as" });
  } catch (e) {
    valid = e.errors[0];
  }
  expect(valid).toBe(config.errMessages.email.format);
});

I'm going to assume that this issue is somewhat related #38.

Custom Email Format Error shows built-in Error instead

Ran the following test and the assertion failed.

let valid;
let message = {
  title: "email",
  type: "object",
  properties: {
    email: {
      type: "string",
      format: "email"
    }
  }
};
let config = {
  errMessages: {
    email: {
      format: "Email format incorrect"
    }
  }
};

// Below test fails
// Expects "Email format incorrect" but returns "email must be a valid email"
it("yup inserts custom messages for email format", () => {
  try {
    const yupSchema = buildYup(message, config);
    valid = yupSchema.validateSync({ email: "as" });
  } catch (e) {
    valid = e.errors[0];
  }
  expect(valid).toBe(config.errMessages.email.format);
});

Typescript version

Continuing the conversation from #19...

Thank you for the detailed reply. I thought it would help if I first gave a little background info on how I became interested in this library...

At my company, we will be building a mostly custom CMS for our needs, and I am currently looking into options for designing and implementing validation. We are still in the evaluation stage, but this library certainly looks promising. We are planning to use Formik, which has a built-in integration for Yup, so my idea was that we could retrieve the list of validation rules for our forms from the backend via GraphQL and generate a Yup schema from them. Our main goal is just to define validation rules once and execute them on both the backend (written in .NET) and the frontend (except for validation that can only be done on the backend of course). While it would be possible to do a conversion to JSON schema on the backend, I'm not sure it's worth the effort since our backend architecture does not require JSON schema, and it would just be an extra step on the way to a Yup schema on the frontend. So I like the fact that this library allows you to customize the mapping so you can use other formats besides JSON schema as input.

We are still evaluating options as I mentioned, but assuming things go according to plan, I would be happy to collaborate on this library.

What version of Typescript did you use to compile it most recently? I pulled down your latest commit but am still seeing a bunch of errors when I attempt to compile, for example:

src/constraints/base.ts:30:14 - error TS2339: Property 'isArrayType' does not exist on type 'Constraint'.

30 if (this.isArrayType(value))

I'm also wondering if you have any files on your local machine that didn't get committed...there are a bunch of errors about missing modules, e.g.:

src/base/index.ts:1:26 - error TS2307: Cannot find module './defaults'.

1 import { defaults } from "./defaults";

I can help fix errors, but since you apparently are already compiling successfully, I thought it would make sense to try to reproduce your working environment first.

Always returns valid

Hi,

Thanks for an amazing project. This is just what we need. Only problem is we are only getting valid results when using the library:


const json = {
  "title":"users",
  "type":"object",
  "required": ["username","first_name","last_name","id_number"],
  "properties":{
    "username":{"type":"string","required":true},
    "first_name":{"type":"string","required":true},
    "last_name":{"type":"string","required":true},
    "id_number":{"type":"string","minLength":12,"maxLength":13,"required":true}
  }
}

const yupSchema = jsonSchemaToYup.buildYup(json);
//console.log(yupSchema)
const valid = yupSchema.isValidSync({
    "username": 123,
    "foo": "bar",
    "erm": [ "this", "that" ]
});

console.log('Is it valid:' + JSON.stringify(valid))

Is there something wrong with the above? It surely should return false?

ItemsOf got error, when trying to add array in schema

Just trying your complex example and got error Uncaught [itemsOf: Error] TypeError: array.of() sub-schema must be a valid yup schema,

  "title": "Person",
  "description": "A person",
  "type": "object",
  "properties": {
    "name": {
      "description": "Name of the person",
      "type": "string",
      "required": true,
      "matches": "[a-zA-Z- ]+",
      "min": 3,
      "maxLength": 40,
    },
    "age": {
      "description": "Age of person",
      "type": "integer",
      "moreThan": 0,
      "max": 130,
      "default": 32,
      "required": false,
      "nullable": true
    },
    "married": {
      "type": "boolean"
    },
    "boss": {
      "type": "object",
      "noUnknown": [
        "name"
      ],
      "properties": {
        "name": {
          "type": "string",
          "notOneOf": ["Dr. evil", "bad ass"]
        }
      }
    },
    "colleagues": {
      "type": "array",
      "items": {
        "type": "object",
        "propertyNames": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string"
          }
        }
      }
    },
    "programming": {
        "type": "object",
        "properties": {
          "languages": {
            "type": "array",
            "of": {
              "type": "string",
              "enum": ["javascript", "java", "C#"]
            },
            "min": 1,
            "max": 3
          }
        }
      }
    }
  }
}

Dynamic Enum

Great work on this library! Looking forward to using it. I was wondering if it was currently possible to dynamically populate an enum? My use case is that I have templated forms that require the same validation, but populate different options in a select field. For example:

...
"foo": {
    "type": "string",
    "enum": {{ids}},
    "enumTitle": {{names}},
}
...

Is there any approach to specifying something like this? I'm happy to define a custom type/override the entry point if that's a good option, but I wasn't sure based on the README how to go about doing so

YupArray.create is not a function

Thank you so much for working on this library. We're stuck with an uncaught TypeError: YupArray.create is not a function. We received the same error message when we swapped out our code for the one in the complex example. We received the same notification for any schema properties value with a type of array.

Do you have any insight into what we may be doing incorrectly?

Is it possible to check custom types?

If the type is incorrect, Yup provides an error message i.e.:

For example if a user inserts letters in a field that expects an integer the following error message is shown by default:

id must be a `number` type, but the final value was: `NaN` (cast from the value `"asd"`).

As described in this source:
https://til.hashrocket.com/posts/gmuuizvueo-custom-type-checking-error-messages-with-yup

Is it possible to adjust this standard error message when using schema-to-yup or is that something that has nothing to do with schema-to-yup?

NPM vulnerabilities found

Description

  1. Clone the repo
  2. Run npm install

Expected
No errors

Actual
Following message appeared:

found 4 vulnerabilities (1 low, 1 moderate, 2 high)
  run `npm audit fix` to fix them, or `npm audit` for details```

Error complex json

It does not generate validation for complex types, it only generates validation for first level objects.
capture

Uncaught TypeError: this.mixed is not a function

got this error when using date property
thanks

react-dom.development.js:11441 Uncaught TypeError: this.mixed is not a function
at e.toEntry (index.js:798)


properties: {
id: {
description: 'Id',
type: 'string',
// value: uniqid(),
required: true,
// label
},
edate: {
description: 'Evaluation Date',
type: 'date',
// value: moment(),
},
},
// required: ['name', 'age'],
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.