Skip to content

Commit 25dd690

Browse files
Gdewildeclaude
andcommitted
fix: handle null values in enum allowedValues
When a schema defines a nullable enum (e.g., `enum: ['one', 'two', null]`), the `allowedValues` array contains `null`. Calling `null.toString()` throws a TypeError, crashing the error formatter. Replace `.toString()` with `String(value ?? '')` to safely handle null values in enum suggestions. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 24a2786 commit 25dd690

3 files changed

Lines changed: 1876 additions & 1482 deletions

File tree

src/index.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,36 @@ describe('betterAjvErrors', () => {
278278
]);
279279
});
280280

281+
it('should not crash when allowedValues contains null', () => {
282+
data = {
283+
str: 'str',
284+
enum: 'invalid',
285+
};
286+
schema = {
287+
type: 'object',
288+
properties: {
289+
str: { type: 'string' },
290+
enum: {
291+
type: ['string', 'null'],
292+
enum: ['one', 'two', null],
293+
},
294+
},
295+
};
296+
ajv.validate(schema, data);
297+
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
298+
expect(errors).toEqual([
299+
{
300+
context: {
301+
errorType: 'enum',
302+
allowedValues: ['one', 'two', null],
303+
},
304+
message: "'enum' property must be equal to one of the allowed values",
305+
path: '{base}.enum',
306+
suggestion: "Did you mean 'one'?",
307+
},
308+
]);
309+
});
310+
281311
it('should not crash on null value', () => {
282312
data = {
283313
type: null,

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ export const betterAjvErrors = <S = any>({
5555
break;
5656
}
5757
case 'enum': {
58-
const suggestions = error.params.allowedValues.map((value) => value.toString());
58+
const suggestions = error.params.allowedValues.map((value) => String(value ?? ''));
5959
const prop = getLastSegment(error.instancePath);
6060
const value = safeJsonPointer({ object: data, pnter: error.instancePath, fallback: '' });
6161
validationError = {

0 commit comments

Comments
 (0)