Skip to content
Myr

Fix Validation of optional empty/undefined arrays (#690)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* * fix(validator): allow empty and undefined optional arrays fix the bug of empty and undefined array causing a validation fail when those are anyways optional resolves #677 * denonify changes

authored by Dario Piotrowicz · committed by GitHub · parent 86699c1 · Browse files · 3 files+28 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+28 added−2 removed

  • tests:+26 added−0 removed
  • other:+2 added−2 removed

3 files+28 added−2 removed

modified:deno_dist/validator/validator.ts+1 added-1 removed
302 unmodified lines
303304 private validateType = (value: Type): boolean => {305 if (this.isArray) {306 if (!Array.isArray(value)) {307 return false307 return this._optional && typeof value === 'undefined'308 }309 for (const val of value) {310 if (typeof val === 'undefined' && this._nested()) {311 value.pop()
186 unmodified lines
modified:src/validator/validator.test.ts+26 added
370 unmodified lines
371 const results = await validator.validate(req)372 expect(results[0].isValid).toBe(true)373 expect(results[0].value).toEqual([false, true, undefined])374 })375376 ;[undefined, []].forEach(value => {377 it(`Should allow ${value === undefined ? 'undefined' : 'empty'} arrays when optional`, async () => {378 const req = new Request('http://localhost/', {379 method: 'POST',380 body: JSON.stringify({ blog: {381 ...(value === undefined ? {} : { posts: [] })382 } }),383 })384 const vObject = v.object('blog', v => ({385 posts: v.array('posts', v => ({386 id: v.json('id').asNumber().isOptional(),387 title: v.json('title').isOptional(),388 author: v.object('author', v => ({389 name: v.json('name'),390 })).isOptional()391 })).isOptional(),392 highlightedPostId: v.json('highlightedPostId').asNumber(),393 }))394 for (const validator of vObject.getValidators()) {395 const results = await validator.validate(req)396 expect(results[0].isValid).toBe(true)397 expect(results[0].message).toBeUndefined()398 }399 })400 })401})402403describe('Validate with asArray', () => {404 const v = new Validator()
614 unmodified lines
modified:src/validator/validator.ts+1 added-1 removed
302 unmodified lines
303304 private validateType = (value: Type): boolean => {305 if (this.isArray) {306 if (!Array.isArray(value)) {307 return false307 return this._optional && typeof value === 'undefined'308 }309 for (const val of value) {310 if (typeof val === 'undefined' && this._nested()) {311 value.pop()
186 unmodified lines