File tree Expand file tree Collapse file tree 2 files changed +29
-6
lines changed
Expand file tree Collapse file tree 2 files changed +29
-6
lines changed Original file line number Diff line number Diff line change @@ -268,6 +268,22 @@ describe("misc.ts", () => {
268268 } ) ;
269269 } ) ;
270270
271+ it ( "should remove invalid array elements with min size" , ( ) => {
272+ const schema = z
273+ . object ( {
274+ name : z . string ( ) ,
275+ tags : z . array ( z . enum ( [ "coder" , "developer" ] ) ) . min ( 2 ) ,
276+ } )
277+ . partial ( ) ;
278+ const obj = {
279+ name : "Alice" ,
280+ tags : [ "developer" , "unknown" ] as any ,
281+ } ;
282+ expect ( sanitize ( schema , obj ) ) . toEqual ( {
283+ name : "Alice" ,
284+ } ) ;
285+ } ) ;
286+
271287 it ( "should remove entire property if all array elements are invalid" , ( ) => {
272288 const obj = { name : "Alice" , age : 30 , tags : [ 123 , 456 ] as any } ;
273289 const sanitized = sanitize ( schema , obj ) ;
@@ -312,9 +328,9 @@ describe("misc.ts", () => {
312328 arrayOneTwo : [ "one" , "nonexistent" ] ,
313329 } as any ;
314330 expect ( ( ) => {
315- sanitize ( schema . strip ( ) , obj ) ;
331+ sanitize ( schema . required ( ) . strip ( ) , obj ) ;
316332 } ) . toThrowError (
317- "unable to sanitize: arrayOneTwo: Array must contain at least 2 element(s) "
333+ "unable to sanitize: name: Required, age: Required, tags: Required, enumArray: Required "
318334 ) ;
319335 } ) ;
320336 } ) ;
Original file line number Diff line number Diff line change @@ -754,10 +754,17 @@ export function sanitize<T extends z.ZodTypeAny>(
754754 error . length < value . length //not all items in the array are invalid
755755 ) {
756756 //some items of the array are invalid
757- return [
758- key ,
759- value . filter ( ( _element , index ) => ! error . includes ( index ) ) ,
760- ] ;
757+ const cleanedArray = value . filter (
758+ ( _element , index ) => ! error . includes ( index )
759+ ) ;
760+ const cleanedArrayValidation = schema . safeParse (
761+ Object . fromEntries ( [ [ key , cleanedArray ] ] )
762+ ) ;
763+ if ( cleanedArrayValidation . success ) {
764+ return [ key , cleanedArray ] ;
765+ } else {
766+ return [ key , undefined ] ;
767+ }
761768 } else {
762769 return [ key , undefined ] ;
763770 }
You can’t perform that action at this time.
0 commit comments