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

Allow optional empty #6

Merged
merged 3 commits into from
Jul 31, 2024
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
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