Skip to content

Commit

Permalink
feat(ajv validator): Add a factory createAjvValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
pyoner committed Feb 28, 2020
1 parent 6974fd1 commit 44dcd85
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
8 changes: 3 additions & 5 deletions packages/app/src/App.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import Ajv from "ajv";
import { Form, components } from "@pyoner/svelte-form";
import { Form, components, helpers } from "@pyoner/svelte-form";
import jsonSchemaDraft4 from "ajv/lib/refs/json-schema-draft-04.json";
import * as simple from "./samples/simple";
Expand All @@ -21,9 +21,7 @@
});
ajv.addMetaSchema(jsonSchemaDraft4);
const options = {
ajv
};
const validator = helpers.createAjvValidator(ajv);
let schema, value;
</script>
Expand All @@ -48,7 +46,7 @@
{schema}
{components}
{value}
{options}
{validator}
on:submit={e => {
console.log('submit', e);
}}
Expand Down
15 changes: 9 additions & 6 deletions packages/lib/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import {
Errors,
FormComponents,
Props,
SvelteSchema
SvelteSchema,
Validator
} from './types'

export function createProps<T extends JSONSchemaType, E extends Errors = Error[]>(
Expand Down Expand Up @@ -96,12 +97,14 @@ export const options = {
return ajv
}
}
export function validate(ajv: Ajv.Ajv, schema: JSONSchema, data: JSONSchemaType) {
const valid = ajv.validate(schema, data) as boolean
if (!valid) {
return ajv.errors as Ajv.ErrorObject[]
export function createAjvValidator(ajv: Ajv.Ajv): Validator {
return (schema: JSONSchema, data: JSONSchemaType) => {
const valid = ajv.validate(schema, data) as boolean
if (!valid) {
return errorsToMap(ajv.errors as Ajv.ErrorObject[])
}
return null
}
return null
}

export function errorsToMap(errors: ErrorObject[]): ErrorRecord {
Expand Down

0 comments on commit 44dcd85

Please sign in to comment.