Skip to content

Commit

Permalink
feat(json-schema): add enum validator
Browse files Browse the repository at this point in the history
  • Loading branch information
aitboudad committed Sep 16, 2023
1 parent 0bf7676 commit 087f35c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions demo/src/app/examples/advanced/json-schema/app.module.ts
Expand Up @@ -77,6 +77,7 @@ export function typeValidationMessage({ schemaType }: any) {
{ name: 'maxItems', message: maxItemsValidationMessage },
{ name: 'uniqueItems', message: 'should NOT have duplicate items' },
{ name: 'const', message: constValidationMessage },
{ name: 'enum', message: `must be equal to one of the allowed values` },
],
types: [
{ name: 'null', component: NullTypeComponent, wrappers: ['form-field'] },
Expand Down
14 changes: 14 additions & 0 deletions src/core/json-schema/src/formly-json-schema.service.spec.ts
Expand Up @@ -797,6 +797,20 @@ describe('Service: FormlyJsonschema', () => {
expect(props.multiple).toBeTrue();
});
});

it('should add enum validator', () => {
const schema: JSONSchema7 = {
type: 'integer',
enum: [1, 2, 3],
};
const config = formlyJsonschema.toFieldConfig(schema);

const enumValidators = config.validators.enum;
expect(enumValidators).toBeDefined();
expect(enumValidators(new FormControl(4))).toBeFalse();
expect(enumValidators(new FormControl(5))).toBeFalse();
expect(enumValidators(new FormControl(1))).toBeTrue();
});
});

it('should support const as hidden', () => {
Expand Down
20 changes: 18 additions & 2 deletions src/core/json-schema/src/formly-json-schema.service.ts
Expand Up @@ -411,9 +411,25 @@ export class FormlyJsonschema {
}

if (this.isEnum(schema)) {
field.props.multiple = field.type === 'array';
const enumOptions = this.toEnumOptions(schema);
const multiple = field.type === 'array';

field.type = 'enum';
field.props.options = this.toEnumOptions(schema);
field.props.multiple = multiple;
field.props.options = enumOptions;

const enumValues = enumOptions.map((o) => o.value);
this.addValidator(field, 'enum', ({ value }: AbstractControl) => {
if (value === undefined) {
return true;
}

if (multiple) {
return Array.isArray(value) ? value.every((o) => enumValues.includes(o)) : false;
}

return enumValues.includes(value);
});
}

if (schema.oneOf && !field.type) {
Expand Down

0 comments on commit 087f35c

Please sign in to comment.