Implement validation for empty checkbox selections in CheckboxListInput
- Added useEffect to handle cases where required checkboxes are not selected, setting value to null. - Updated onChange type definition to allow for null values in checkbox selections.
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
import { Box, Checkbox, Field, Flex, Typography } from '@strapi/design-system';
|
import { Box, Checkbox, Field, Flex, Typography } from '@strapi/design-system';
|
||||||
import { useIntl } from 'react-intl';
|
import { useIntl } from 'react-intl';
|
||||||
@@ -6,7 +7,10 @@ import { useIntl } from 'react-intl';
|
|||||||
type CheckboxListInputProps = {
|
type CheckboxListInputProps = {
|
||||||
name: string;
|
name: string;
|
||||||
value?: unknown;
|
value?: unknown;
|
||||||
onChange: (eventOrPath: { target: { name: string; value: string[] } }, value?: unknown) => void;
|
onChange: (
|
||||||
|
eventOrPath: { target: { name: string; value: string[] | null } },
|
||||||
|
value?: unknown
|
||||||
|
) => void;
|
||||||
attribute?: {
|
attribute?: {
|
||||||
enum?: string[];
|
enum?: string[];
|
||||||
options?: {
|
options?: {
|
||||||
@@ -65,6 +69,21 @@ const CheckboxListInput = ({
|
|||||||
const enumValues = getEnumValues(attribute);
|
const enumValues = getEnumValues(attribute);
|
||||||
const selectedValues = normalizeValue(value);
|
const selectedValues = normalizeValue(value);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!required) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(value) && value.length === 0) {
|
||||||
|
onChange({
|
||||||
|
target: {
|
||||||
|
name,
|
||||||
|
value: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [name, onChange, required, value]);
|
||||||
|
|
||||||
const handleToggle = (option: string, isChecked: boolean) => {
|
const handleToggle = (option: string, isChecked: boolean) => {
|
||||||
const nextValues = isChecked
|
const nextValues = isChecked
|
||||||
? Array.from(new Set([...selectedValues, option]))
|
? Array.from(new Set([...selectedValues, option]))
|
||||||
@@ -73,7 +92,7 @@ const CheckboxListInput = ({
|
|||||||
onChange({
|
onChange({
|
||||||
target: {
|
target: {
|
||||||
name,
|
name,
|
||||||
value: nextValues,
|
value: required && nextValues.length === 0 ? null : nextValues,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user