Skip to content
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

fix(next): RMT-1405: fix error messages for conditional schemas #150

Merged
merged 1 commit into from
Mar 20, 2025
Merged
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
49 changes: 30 additions & 19 deletions next/src/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ function validationErrorsToFormErrors(errors: ValidationErrorWithMessage[]): For
return result
}

// For conditional validation branches (then/else), show the error at the field level
const thenElseIndex = Math.max(path.indexOf('then'), path.indexOf('else'))
if (thenElseIndex !== -1) {
const fieldName = path[thenElseIndex + 1]
if (fieldName) {
result[fieldName] = error.message
return result
}
}

// For allOf/anyOf/oneOf validation errors, show the error at the field level
const compositionKeywords = ['allOf', 'anyOf', 'oneOf']
const compositionIndex = compositionKeywords.reduce((index, keyword) => {
Expand All @@ -64,29 +74,24 @@ function validationErrorsToFormErrors(errors: ValidationErrorWithMessage[]): For
}, -1)

if (compositionIndex !== -1) {
// Get the field path (everything before the composition keyword)
// Get the field path before the composition keyword
const fieldPath = path.slice(0, compositionIndex)
let current = result

// Process all segments except the last one (which will hold the message)
fieldPath.slice(0, -1).forEach((segment) => {
// If this segment doesn't exist yet or is currently a string (from a previous error),
// initialize it as an object
if (!(segment in current) || typeof current[segment] === 'string') {
current[segment] = {}
}
if (fieldPath.length > 0) {
let current = result

// Cast is safe because we just ensured it's an object
current = current[segment] as FormErrors
})
// Process all segments except the last one
fieldPath.slice(0, -1).forEach((segment) => {
if (!(segment in current) || typeof current[segment] === 'string') {
current[segment] = {}
}
current = current[segment] as FormErrors
})

// Set the message at the field level
if (fieldPath.length > 0) {
// Set the message at the last segment
const lastSegment = fieldPath[fieldPath.length - 1]
current[lastSegment] = error.message
return result
}

return result
}

// For all other paths, recursively build the nested structure
Expand All @@ -100,8 +105,7 @@ function validationErrorsToFormErrors(errors: ValidationErrorWithMessage[]): For
current[segment] = {}
}

// Cast is safe because we just ensured it's an object
current = current[segment] as FormErrors
current = current[segment]
})

// Set the message at the final level
Expand Down Expand Up @@ -144,6 +148,11 @@ function getSchemaAndValueAtPath(rootSchema: JsfSchema, rootValue: SchemaValue,
else if (segment === 'oneOf' && currentSchema.oneOf) {
continue
}
// Skip the 'then' and 'else' segments, the next segment will be the field name
else if ((segment === 'then' || segment === 'else') && currentSchema[segment]) {
currentSchema = currentSchema[segment]
continue
}
// If we have we are in a composition context, get the subschema
else if (currentSchema.allOf || currentSchema.anyOf || currentSchema.oneOf) {
const index = Number(segment)
Expand Down Expand Up @@ -248,6 +257,8 @@ function validate(value: SchemaValue, schema: JsfSchema, options: ValidationOpti
const result: ValidationResult = {}
const errors = validateSchema(value, schema, options)

// console.log(errors)

// Apply custom error messages before converting to form errors
const errorsWithMessages = addErrorMessages(value, schema, errors)
const processedErrors = applyCustomErrorMessages(errorsWithMessages, schema)
Expand Down
1 change: 0 additions & 1 deletion next/src/validation/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ export function validateSchema(
...validateObject(value, schema, options, path),
...validateString(value, schema, path),
...validateNumber(value, schema, path),
...validateCondition(value, schema, options, required, path),
...validateNot(value, schema, options, path),
...validateAllOf(value, schema, options, path),
...validateAnyOf(value, schema, options, path),
Expand Down
121 changes: 121 additions & 0 deletions next/test/errors/messages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,5 +573,126 @@ describe('validation error messages', () => {
nested: 'The option "ab" is not valid.',
})
})

it('shows conditional validation error messages', () => {
const schema: JsfObjectSchema = {
type: 'object',
properties: {
is_full_time: {
type: 'string',
oneOf: [{ const: 'yes' }, { const: 'no' }],
},
hours: {
type: 'number',
},
},
allOf: [
{
if: {
properties: {
is_full_time: { const: 'yes' },
},
required: ['is_full_time'],
},
then: {
properties: {
hours: {
minimum: 40,
},
},
},
else: {
properties: {
hours: {
minimum: 10,
},
},
},
},
],
}
const form = createHeadlessForm(schema)

// Test full-time validation
const result1 = form.handleValidation({
is_full_time: 'yes',
hours: 5,
})

expect(result1.formErrors).toMatchObject({
hours: 'Must be greater or equal to 40',
})

// Test part-time validation
const result2 = form.handleValidation({
is_full_time: 'no',
hours: 5,
})

expect(result2.formErrors).toMatchObject({
hours: 'Must be greater or equal to 10',
})
})

it('shows conditional validation error messages when only one of the then branch is present', () => {
const schema: JsfObjectSchema = {
type: 'object',
properties: {
num: { type: 'number' },
big: { type: 'string', enum: ['yes', 'no'] },
},
if: {
properties: {
big: { const: 'yes' },
},
},
then: {
properties: {
num: { minimum: 10 },
},
},
}
const form = createHeadlessForm(schema)

expect(form.handleValidation({
num: 5,
big: 'yes',
}).formErrors).toMatchObject({
num: 'Must be greater or equal to 10',
})

expect(form.handleValidation({
num: 5,
big: 'no',
}).formErrors).toBeUndefined()
})

it('shows conditional validation error messages when only one of the else branch is present', () => {
const schema: JsfObjectSchema = {
type: 'object',
properties: {
num: { type: 'number' },
big: { type: 'string', enum: ['yes', 'no'] },
},
if: {
properties: {
big: { const: 'yes' },
},
},
else: {
properties: {
num: { minimum: 10 },
},
},
}
const form = createHeadlessForm(schema)

expect(form.handleValidation({
num: 5,
big: 'no',
}).formErrors).toMatchObject({
num: 'Must be greater or equal to 10',
})
})
})
})
Loading