@@ -820,3 +820,62 @@ describe('Array validation', () => {
820820 } ) ;
821821 } ) ;
822822} ) ;
823+
824+ describe ( 'Enum validation' , ( ) => {
825+ const fishes = [ 'trout' , 'tuna' , 'shark' ] as const ;
826+
827+ const schema = z . object ( {
828+ fish : z . enum ( fishes ) ,
829+ moreFish : z . enum ( fishes )
830+ } ) ;
831+
832+ const schema2 = schema . extend ( {
833+ fish : schema . shape . fish . nullable ( ) ,
834+ moreFish : schema . shape . moreFish . optional ( )
835+ } ) ;
836+
837+ describe ( 'With FormData' , ( ) => {
838+ it ( 'should not return the default first enum value when an empty string is posted' , async ( ) => {
839+ const formData = new FormData ( ) ;
840+ const adapter = zod ( schema ) ;
841+ const form = await superValidate ( formData , adapter ) ;
842+ assert ( form . valid ) ;
843+ expect ( form . data ) . toEqual ( { fish : 'trout' , moreFish : 'trout' } ) ;
844+
845+ formData . set ( 'fish' , '' ) ;
846+ const form2 = await superValidate ( formData , adapter ) ;
847+ assert ( ! form2 . valid ) ;
848+ expect ( form2 . data ) . toEqual ( { fish : '' , moreFish : 'trout' } ) ;
849+ expect ( form2 . errors . fish ?. [ 0 ] ) . toMatch ( / ^ I n v a l i d e n u m v a l u e \. / ) ;
850+ } ) ;
851+
852+ it ( 'should still work with undefined or nullable' , async ( ) => {
853+ const formData = new FormData ( ) ;
854+ const adapter = zod ( schema2 ) ;
855+ const form = await superValidate ( formData , adapter ) ;
856+ assert ( form . valid ) ;
857+ expect ( form . data ) . toEqual ( { fish : null , moreFish : undefined } ) ;
858+
859+ formData . set ( 'fish' , '' ) ;
860+ const form2 = await superValidate ( formData , adapter ) ;
861+ assert ( form2 . valid ) ;
862+ expect ( form2 . data ) . toEqual ( { fish : null , moreFish : undefined } ) ;
863+ } ) ;
864+ } ) ;
865+
866+ describe ( 'With data objects' , ( ) => {
867+ it ( 'should add the default enum value if field does not exist' , async ( ) => {
868+ const adapter = zod ( schema ) ;
869+ const form = await superValidate ( { } , adapter ) ;
870+ assert ( form . valid ) ;
871+ expect ( form . data ) . toEqual ( { fish : 'trout' , moreFish : 'trout' } ) ;
872+ } ) ;
873+
874+ it ( 'should add the default null/undefined if field does not exist' , async ( ) => {
875+ const adapter = zod ( schema2 ) ;
876+ const form = await superValidate ( { } , adapter ) ;
877+ assert ( form . valid ) ;
878+ expect ( form . data ) . toEqual ( { fish : null , moreFish : undefined } ) ;
879+ } ) ;
880+ } ) ;
881+ } ) ;
0 commit comments