Skip to content

feat(next): Custom user defined validations #196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions next/src/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { getErrorMessage } from './errors/messages'
import { buildFieldSchema } from './field/schema'
import { calculateFinalSchema, updateFieldProperties } from './mutations'
import { validateSchema } from './validation/schema'
import { registerCustomFunctionsToJsonLogic } from './validation/json-logic'

export { ValidationOptions } from './validation/schema'

Expand Down Expand Up @@ -255,6 +256,10 @@ export function createHeadlessForm(
options: options.validationOptions,
})

if (options.validationOptions?.customJsonLogicOps) {
registerCustomFunctionsToJsonLogic(options.validationOptions.customJsonLogicOps)
}

const fields = buildFields({ schema: updatedSchema, originalSchema: schema, strictInputType })

// TODO: check if we need this isError variable exposed
Expand Down
10 changes: 10 additions & 0 deletions next/src/validation/json-logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ import type { ValidationError, ValidationErrorPath } from '../errors'
import type { JsfObjectSchema, JsfSchema, JsonLogicContext, JsonLogicRules, JsonLogicSchema, NonBooleanJsfSchema, ObjectValue, SchemaValue } from '../types'
import jsonLogic from 'json-logic-js'

/**
* Register user defined functions to be used in JSON Logic rules.
* @param customJsonLogicOps An object containing custom JSON Logic operations to register
*/
export function registerCustomFunctionsToJsonLogic(customJsonLogicOps: Record<string, (...args: any[]) => any>) {
for (const [name, func] of Object.entries(customJsonLogicOps)) {
jsonLogic.add_operation(name, func)
}
}

/**
* Builds a json-logic context based on a schema and the current value
* @param schema - The schema to build the context from
Expand Down
6 changes: 6 additions & 0 deletions next/src/validation/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export interface ValidationOptions {
* @default false
*/
allowForbiddenValues?: boolean

/**
* Custom jsonLogic operations to register (only applies once at setup)
* Format: { [operationName]: (...args: any[]) => any }
*/
customJsonLogicOps?: Record<string, (...args: any[]) => any>
}

/**
Expand Down
24 changes: 23 additions & 1 deletion next/test/validation/json-logic-v0.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createHeadlessForm } from '@/createHeadlessForm'
import { afterEach, beforeEach, describe, expect, it } from '@jest/globals'

import { mockConsole, restoreConsoleAndEnsureItWasNotCalled } from '../test-utils'

import {
badSchemaThatWillNotSetAForcedValue,
createSchemaWithRulesOnFieldA,
Expand All @@ -15,6 +16,7 @@ import {
schemaWithComputedAttributeThatDoesntExist,
schemaWithComputedAttributeThatDoesntExistDescription,
schemaWithComputedAttributeThatDoesntExistTitle,
schemaWithCustomValidationFunction,
schemaWithDeepVarThatDoesNotExist,
schemaWithDeepVarThatDoesNotExistOnFieldset,
schemaWithInlinedRuleOnComputedAttributeThatReferencesUnknownVar,
Expand All @@ -30,6 +32,7 @@ import {
schemaWithUnknownVariableInValidations,
schemaWithValidationThatDoesNotExistOnProperty,
} from './json-logic.fixtures'
import { createHeadlessForm } from '@/createHeadlessForm'

beforeEach(mockConsole)
afterEach(restoreConsoleAndEnsureItWasNotCalled)
Expand Down Expand Up @@ -446,4 +449,23 @@ describe('jsonLogic: cross-values validations', () => {
expect(handleValidation({ field_a: 20, field_b: 41 }).formErrors).toEqual()
})
})

describe('custom operators', () => {
it('custom function', () => {
const { handleValidation } = createHeadlessForm(schemaWithCustomValidationFunction, { strictInputType: false, validationOptions: { customJsonLogicOps: { is_hello: a => a === 'hello world' } } })
expect(handleValidation({ field_a: 'hello world' }).formErrors).toEqual(undefined)
const { formErrors } = handleValidation({ field_a: 'wrong text' })
expect(formErrors?.field_a).toEqual('Invalid hello world')
})

it('custom function are form specific', () => {
const { handleValidation } = createHeadlessForm(schemaWithCustomValidationFunction, { strictInputType: false, validationOptions: { customJsonLogicOps: { is_hello: a => a === 'hello world' } } })
expect(handleValidation({ field_a: 'hello world' }).formErrors).toEqual(undefined)
const { formErrors } = handleValidation({ field_a: 'wrong text' })
expect(formErrors?.field_a).toEqual('Invalid hello world')

const { handleValidation: handleValidation2 } = createHeadlessForm(schemaWithCustomValidationFunction, { strictInputType: false, validationOptions: { customJsonLogicOps: { is_hello: a => a === 'hello world!' } } })
expect(handleValidation2({ field_a: 'hello world!' }).formErrors).toEqual(undefined)
})
})
})
19 changes: 19 additions & 0 deletions next/test/validation/json-logic.fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -744,3 +744,22 @@ export const schemaWithReduceAccumulator = {
},
},
}

export const schemaWithCustomValidationFunction = {
'properties': {
field_a: {
'type': 'string',
'x-jsf-logic-validations': ['hello_world'],
},
},
'x-jsf-logic': {
validations: {
hello_world: {
errorMessage: 'Invalid hello world',
rule: {
is_hello: { var: 'field_a' },
},
},
},
},
}