Skip to content

Commit

Permalink
allow empty values when optional
Browse files Browse the repository at this point in the history
  • Loading branch information
skbolton authored Jul 31, 2024
2 parents b8c55ab + 63835dd commit c391aa1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
20 changes: 20 additions & 0 deletions lib/schema/__test__/validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ describe('validator(field, config)', () => {
expect(result).toBeInstanceOf(Date)
})

it('should return the value if it is undefined and not required and a default is not set', () => {
delete config.required
delete config.default

const validate = validator('string', config)
const result = validate(null)

expect(result).toBeNull()
});

it('should return the value if it is an emum, undefined and not required and a default is not set', () => {
delete ofConfig.required

const validate = validator('enum', ofConfig)
const result = validate(null)

expect(result).toBeNull()
});


it('should return error when default is different than type', () => {
const badConfig = {
required: true,
Expand Down
13 changes: 12 additions & 1 deletion lib/schema/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ const functionizeConfig = (field, config) => {
_config.default = always(config.default)
}
if (config.enum) {

_config.enum = value => {
// Don't validate enums if they are optional and not set
if (!config.required && (value === undefined || value === null)) {
return value
}

if (!contains(value, config.enum)) {
throw new Error(
`Field ${field} only accpets [ ${config.enum.join(', ')} ]. Instead got ${value}`
`Field ${field} only accepts [ ${config.enum.join(', ')} ]. Instead got ${value}`
)
} else {
return value
Expand All @@ -44,6 +50,11 @@ const functionizeConfig = (field, config) => {
}
if (config.type) {
_config.type = value => {
// Don't validate the value if it is optional and not set
if (!config.required && (value === undefined || value === null)) {
return value
}

const type = valid[config.type.toLowerCase()]
const isValid = type(value)
if (isValid !== null) {
Expand Down

0 comments on commit c391aa1

Please sign in to comment.