Skip to content

Commit

Permalink
also allow null in required select/radio fields
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrina-p committed Jul 3, 2023
1 parent a1deee5 commit 93fbd2e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
9 changes: 8 additions & 1 deletion src/tests/createHeadlessForm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -440,10 +440,17 @@ describe('createHeadlessForm', () => {
[fieldName]: 'Required field',
});

// Given empty string (""), it also complaints it's required.
// As required field, empty string ("") is also considered empty. @BUG RMT-518
// Expectation: The error to be "The option '' is not valid."
expect(validateForm({ [fieldName]: '' })).toEqual({
[fieldName]: 'Required field',
});

// As required field, null is also considered empty @BUG RMT-518
// Expectation: The error to be "The option null is not valid."
expect(validateForm({ [fieldName]: null })).toEqual({
[fieldName]: 'Required field',
});
}

it('support "text" field type', () => {
Expand Down
17 changes: 12 additions & 5 deletions src/yupSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,23 @@ const getJsonTypeInArray = (jsonType) =>

const getOptionsAllowed = (field) => {
const onlyValues = field.options?.map((option) => option.value);
const optionsBroken = [...onlyValues, '']; /*[1]*/
const optionsBroken = [
...onlyValues,
'', // [1]
];

if (field.required) {
return optionsBroken;
return [
...optionsBroken,
null, // [2]
];
}

const isOptionalWithNull =
Array.isArray(field.jsonType) &&
// @TODO should also check the "oneOf" directly looking for "null" option
// but we don't have direct access at this point. Otherwise
// the JSON Schema validator will fail because setting jsonType is not enough.
// @TODO should also check the "oneOf" directly looking for "null"
// option but we don't have direct access at this point.
// Otherwise the JSON Schema validator will fail as explained in PR#18
field.jsonType.includes('null');
if (isOptionalWithNull) {
return [...optionsBroken, null];
Expand All @@ -112,6 +118,7 @@ const getOptionsAllowed = (field) => {
This is a dangerous change as it can disrupt existing UI Form integrations
that might handle empty fields differently ("" vs null vs undefined).
[2] The null also needs to be always accepted for the same reason.
We'd need to implement a feature_flag/transition deprecation warning
to give devs the time to adapt their integrations before we fix this behavior.
Expand Down

0 comments on commit 93fbd2e

Please sign in to comment.