File tree 2 files changed +23
-5
lines changed
2 files changed +23
-5
lines changed Original file line number Diff line number Diff line change @@ -91,7 +91,19 @@ describe('Validations', () => {
91
91
} ) ;
92
92
describe ( 'required()' , ( ) => {
93
93
const errorMessage = 'You must answer this question before continuing' ;
94
- const subject = required ( ) ;
94
+ const subject = required ( true ) ;
95
+
96
+ it ( 'handles initialisation with boolean or string to determine message' , ( ) => {
97
+ const withBooleanMessage = required ( true ) ;
98
+ const withStringMessage = required ( 'Custom message' ) ;
99
+
100
+ expect ( withBooleanMessage ( '' ) ) . toBe (
101
+ 'You must answer this question before continuing' ,
102
+ ) ;
103
+ expect ( withStringMessage ( '' ) ) . toBe ( 'Custom message' ) ;
104
+ expect ( withStringMessage ( 'hello' ) ) . toBe ( undefined ) ;
105
+ expect ( withBooleanMessage ( 'hello' ) ) . toBe ( undefined ) ;
106
+ } ) ;
95
107
96
108
it ( 'passes for a string' , ( ) => {
97
109
expect ( subject ( 'hello world' ) ) . toBe ( undefined ) ;
Original file line number Diff line number Diff line change @@ -43,13 +43,19 @@ const coerceArray = (value: FieldValue) => {
43
43
// to be able to specify a string for the message in some cases. A better
44
44
// design would probably be to have a separate validation function for
45
45
// required that takes a message.
46
- export const required = ( message ? : string | boolean ) => ( value : FieldValue ) => {
46
+ export const required = ( message : string | true ) => ( value : FieldValue ) => {
47
47
const isEmptyString = isString ( value ) && value . length === 0 ;
48
48
49
49
if ( isNil ( value ) || isEmptyString ) {
50
- return typeof message === 'boolean' && message === true
51
- ? 'You must answer this question before continuing'
52
- : message ;
50
+ // If initialised with a string, assume required is true
51
+ // and return the string as the message
52
+ if ( typeof message === 'string' ) {
53
+ return message ;
54
+ }
55
+
56
+ // Otherwise, return the default message. Note: 'false' is not handled because
57
+ // we have never used it.
58
+ return 'You must answer this question before continuing' ;
53
59
}
54
60
55
61
return undefined ;
You can’t perform that action at this time.
0 commit comments