https://github.com/aeberdinelli/schemy-reference-support
Add reference support to Schemy
https://github.com/aeberdinelli/schemy-reference-support
javascript json node schema schemy validation
Last synced: 2 months ago
JSON representation
Add reference support to Schemy
- Host: GitHub
- URL: https://github.com/aeberdinelli/schemy-reference-support
- Owner: aeberdinelli
- Created: 2021-08-28T19:17:36.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2021-09-07T02:35:14.000Z (almost 5 years ago)
- Last Synced: 2025-01-12T11:30:43.423Z (over 1 year ago)
- Topics: javascript, json, node, schema, schemy, validation
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/schemy-reference-support
- Size: 8.79 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Reference support
## Introduction
This [Schemy](https://github.com/aeberdinelli/schemy) plugin adds the functionality to reference values from within a schema using `Schemy.$ref()`.
## Install
- `npm install --save schemy-reference-support`
## Usage
Add the plugin to Schemy:
```javascript
const Schemy = require('schemy');
const SchemyReferenceSupport = require('schemy-reference-support');
// Load the plugin into Schemy
Schemy.extend(SchemyReferenceSupport);
// Now you can use Schemy.$ref(propertyName)
```
## Examples
### In property settings
We can use a previously defined property within the definition of the schema. In the following example we set the max elements for an array using the `maxItems` property.
```javascript
const schema = new Schemy({
maxItems: {
type: Number,
required: true
},
items: {
type: [String],
max: Schemy.$ref('maxItems')
}
});
schema.validate({
maxItems: 1,
items: ['one','two']
}); // => false
schema.getValidationErrors(); // => [ 'Property items must contain no more than 1 elements' ]
```
### Direct reference
We can also reference directly to a property if we want two properties to match. This is useful for password confirmation:
```javascript
const schema = new Schemy({
username: String,
password: String,
confirm: Schemy.$ref('password')
});
schema.validate({
username: 'schemy',
password: 'password1',
confirm: 'password2'
}); // => false
schema.getValidationErrors(); // => [ 'Property confirm does not match referenced value: password' ]
```
## Notes
- Requires Schemy version **>= 3.2.1**