How to use is-my-json-valid - 10 common examples

To help you get started, we’ve selected a few is-my-json-valid examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Automattic / wp-calypso / client / lib / make-json-schema-parser / index.js View on Github external
const genParser = () => {
		const options = Object.assign( { greedy: true, verbose: true }, schemaOptions );
		const validator = schemaValidator( schema, options );

		// filter out unwanted properties even though we may have let them slip past validation
		// note: this property does not nest deeply into the data structure, that is, properties
		// of a property that aren't in the schema could still come through since only the top
		// level of properties are pruned
		const filter = schemaValidator.filter(
			Object.assign(
				{},
				schema,
				schema.type && schema.type === 'object' && { additionalProperties: false }
			)
		);

		validate = data => {
			if ( ! validator( data ) ) {
				if ( 'development' === process.env.NODE_ENV ) {
					// eslint-disable-next-line no-console
					console.warn( 'JSON Validation Failure' );

					validator.errors.forEach( error =>
						// eslint-disable-next-line no-console
						console.warn( {
github Automattic / wp-calypso / client / components / domains / registrant-extra-info / fr-validate-contact-details.js View on Github external
/**
 * External dependencies
 */

import { isEmpty, isString, reduce, update } from 'lodash';
import validatorFactory from 'is-my-json-valid';
import debugFactory from 'debug';

/**
 * Internal dependencies
 */
import validationSchema from './fr-schema';

const validate = validatorFactory( validationSchema, { greedy: true } );
const debug = debugFactory( 'calypso:components:domains:registrant-extra-info:validation' );

// is-my-json-valid uses customized messages, but the actual rule name seems
// more intuitive
// See http://json-schema.org/latest/json-schema-validation.html#rfc.section.6
// Notes:
// - Looks like is-my-json-valid does not handle contains
// - `items` doesn't get it's own message, it just adds an index to the path
//   e.g. If you validate `{ even: [ 0, 1, 2, 3 ] }`` using the schema
//   `{ properties: { even: { items: { multipleOf: 2 } } } }` you get errors
//   with field 'data.even.1' and `data.even.2`.
// - patternProperties is similar to items, but less readable.
const reverseMessageMap = {
	'is required': 'required',
	'is the wrong type': 'type',
	'has additional items': 'additionalItems',
github Automattic / wp-calypso / client / components / domains / registrant-extra-info / with-contact-details-validation.jsx View on Github external
compileValidator() {
			// The schema object we compile is available at this.validate.toJSON()
			// but we already check it's different in componentWillReceiveProps
			debug( `compiling validation schema for ${ tld }`, this.props.validationSchema );
			this.validate = validatorFactory( this.props.validationSchema, {
				greedy: true,
				verbose: true,
			} );
		}
github carlansley / swagger2 / src / document.ts View on Github external
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

import jsonValidator from 'is-my-json-valid';
import * as YAML from 'yamljs';

import { Document } from './schema';
import * as schema from './schema.json';

// build a swagger validator from the official v2.0 schema
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const schemaValidator = jsonValidator(schema as any);

/*
 * Validate a swagger document against the 2.0 schema, returning a typed Document object.
 */
export function validateDocument(document: unknown): Document | undefined {
  if (!schemaValidator(document)) {
    return;
  }
  return document as Document;
}

/*
 * Load a swagger document.  We only support YAML for now.
 */
export function loadDocumentSync(file: string): unknown {
  return YAML.load(file);
github carlansley / swagger2 / src / compiler.ts View on Github external
function stringValidator(schema: any) {
  const validator = jsonValidator(schema);
  return (inputValue: any) => {
    // if an optional field is not provided, we're all good other not so much
    if (typeof inputValue === 'undefined') {
      return !schema.required;
    }

    let value = inputValue;

    switch (schema.type) {
      case 'number':
      case 'integer':
        if (!isNaN(value)) {
          // if the value is a number, make sure it's a number
          value = Number(value);
        }
        break;
github Automattic / wp-calypso / client / state / utils / schema-utils.js View on Github external
export function isValidStateWithSchema( state, schema, debugInfo ) {
	const validate = validator( schema, {
		greedy: process.env.NODE_ENV !== 'production',
		verbose: process.env.NODE_ENV !== 'production',
	} );
	const valid = validate( state );
	if ( ! valid && process.env.NODE_ENV !== 'production' ) {
		const msgLines = [ 'State validation failed.', 'State: %o', '' ];
		const substitutions = [ state ];

		forEach( validate.errors, ( { field, message, schemaPath, value } ) => {
			// data.myField is required
			msgLines.push( '%s %s' );
			substitutions.push( field, message );

			// Found: { my: 'state' }
			msgLines.push( 'Found: %o' );
			substitutions.push( value );
github Automattic / woocommerce-services / client / state / selectors.js View on Github external
const memoizedValidator = memoize( ( schema ) => validator( schema, { greedy: true } ) );
github rstuven / fsa-creator / src / createAction.js View on Github external
function validatedIdentity(schema, name) {
  const validate = validator(schema);
  return value => {
    if (validate(value)) {
      return value;
    }
    const { field, message } = validate.errors[0];
    return new Error(`${field.replace(/^data/, name)} ${message}`);
  };
}
github carlansley / swagger2 / src / compiler.ts View on Github external
operation.resolvedParameters.forEach((parameter: CompiledParameter) => {
          const schema = parameter.schema || parameter;
          if (parameter.in === 'query' || parameter.in === 'header' || parameter.in === 'path') {
            parameter.validator = stringValidator(schema);
          } else {
            parameter.validator = jsonValidator(schema);
          }
        });
github Automattic / wp-calypso / client / __mocks__ / is-my-json-valid.js View on Github external
export default function validator( schema, options ) {
	throwOnInvalidSchema( schema );
	return imjv( schema, options );
}

is-my-json-valid

A [JSONSchema](https://json-schema.org/) validator that uses code generation to be extremely fast.

MIT
Latest version published 3 years ago

Package Health Score

74 / 100
Full package analysis