This repository was archived by the owner on May 11, 2021. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -201,6 +201,35 @@ it('allows converting a number into a string', () => {
201
201
} )
202
202
} )
203
203
204
+ it ( 'allows coercing a boolean string/number into a boolean' , ( ) => {
205
+ const result1 = validateObjectShape (
206
+ 'Test obj' ,
207
+ {
208
+ testBooleanNumber : 1 ,
209
+ testBooleanNumberFalse : 0 ,
210
+ testBooleanString : 'true' ,
211
+ testBooleanStringFalse : 'false'
212
+ } ,
213
+ {
214
+ testBooleanNumber : 'boolean' ,
215
+ testBooleanNumberFalse : 'boolean' ,
216
+ testBooleanString : 'boolean' ,
217
+ testBooleanStringFalse : 'boolean'
218
+ } ,
219
+ { coerceBooleans : true }
220
+ )
221
+
222
+ expect ( result1 ) . toMatchObject ( {
223
+ valid : true ,
224
+ result : {
225
+ testBooleanNumber : true ,
226
+ testBooleanNumberFalse : false ,
227
+ testBooleanString : true ,
228
+ testBooleanStringFalse : false
229
+ }
230
+ } )
231
+ } )
232
+
204
233
it ( 'when wrapping an item in a array ensure it coerced correctly' , ( ) => {
205
234
const result1 = validateObjectShape (
206
235
'Test obj' ,
Original file line number Diff line number Diff line change @@ -54,6 +54,7 @@ export interface ValidationOptions {
54
54
* be valid if inside an array, it will automatically be wrapped
55
55
*/
56
56
coerceValidObjectIntoArray ?: boolean
57
+ coerceBooleans ?: boolean
57
58
}
58
59
59
60
export interface OptionalShape < T > {
@@ -240,6 +241,15 @@ export function validateValue<T extends ValidationKeyType<any>>(
240
241
241
242
if ( valueType === 'boolean' ) {
242
243
if ( typeof value !== 'boolean' ) {
244
+ if ( options . coerceBooleans ) {
245
+ if ( value === 'true' || value === 1 ) {
246
+ return { valid : true , result : true }
247
+ }
248
+ if ( value === 'false' || value === 0 ) {
249
+ return { valid : true , result : false }
250
+ }
251
+ }
252
+
243
253
const errorMessage = `Expected ${ valueDescription } to be type: boolean, was ${ typeof value } `
244
254
return {
245
255
valid : false ,
You can’t perform that action at this time.
0 commit comments