Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

form: infer optional fields from validator schema

Sid Gaikwadae51dcc8e439
diff --git a/apps/erp/app/components/Form/UnitHint.tsx b/apps/erp/app/components/Form/UnitHint.tsx
index 4661465243..f0913f0563 100644
--- a/apps/erp/app/components/Form/UnitHint.tsx
+++ b/apps/erp/app/components/Form/UnitHint.tsx
@@ -1,3 +1,4 @@
+import { useField } from "@carbon/form";
import { FormControl, FormHelperText, FormLabel } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
@@ -6,9 +7,11 @@ import type { SelectProps } from "~/components/Select";
import type { StandardFactor } from "~/modules/shared";
export type UnitHintProps = Omit<SelectProps, "onChange" | "options"> & {
+ name: string;
defaultUnit?: StandardFactor;
label?: string;
helperText?: string;
+ isOptional?: boolean;
isConfigured?: boolean;
value: string;
onChange: (newValue: string) => void;
@@ -23,12 +26,15 @@ const UnitHint = ({
name,
label,
helperText,
+ isOptional,
isConfigured,
value = getUnitHint(defaultUnit),
onConfigure,
...props
}: UnitHintProps) => {
const { t } = useLingui();
+ const { isOptional: fieldIsOptional } = useField(name);
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
const onChange = (value: string) => {
props?.onChange?.(value);
@@ -43,6 +49,7 @@ const UnitHint = ({
<FormLabel
htmlFor={name}
isConfigured={isConfigured}
+ isOptional={resolvedIsOptional}
onConfigure={onConfigure}
>
{label}
diff --git a/apps/erp/app/components/Selectors/UserSelect/types.ts b/apps/erp/app/components/Selectors/UserSelect/types.ts
index c68ddc311d..ee2ea9717d 100644
--- a/apps/erp/app/components/Selectors/UserSelect/types.ts
+++ b/apps/erp/app/components/Selectors/UserSelect/types.ts
@@ -33,6 +33,7 @@ export interface UserSelectProps {
| null;
isMulti?: boolean;
label?: string;
+ isOptional?: boolean;
placeholder?: string;
showAvatars?: boolean;
queryFilters?: UserSelectionGenericQueryFilters;
diff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsx
index 42cd7c9f71..68ebdcf421 100644
--- a/packages/form/src/ValidatedForm.tsx
+++ b/packages/form/src/ValidatedForm.tsx
@@ -293,9 +293,10 @@ export function ValidatedForm<
action,
subaction,
defaultValuesProp: providedDefaultValues,
- fetcher
+ fetcher,
+ validatorSchema: validator
}),
- [action, fetcher, formId, providedDefaultValues, subaction]
+ [action, fetcher, formId, providedDefaultValues, subaction, validator]
);
const formStateValue = useMemo(
() => ({ isDisabled, isReadOnly }),
diff --git a/packages/form/src/components/Array.tsx b/packages/form/src/components/Array.tsx
index 110d7f6c5b..baa3f03601 100644
--- a/packages/form/src/components/Array.tsx
+++ b/packages/form/src/components/Array.tsx
@@ -34,11 +34,13 @@ const Array = forwardRef<HTMLInputElement, FormArrayProps>(
},
ref
) => {
+ const { isOptional: fieldIsOptional } = useField(name);
const listRef = useRef<HTMLDivElement>(null);
const [items, { push, remove }, error] = useFieldArray<string>(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || isDisabledProp;
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
+ const resolvedIsOptional = isRequired ? false : (fieldIsOptional ?? false);
const onAdd = () => {
flushSync(() => {
push("");
@@ -51,7 +53,11 @@ const Array = forwardRef<HTMLInputElement, FormArrayProps>(
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
- {label && <FormLabel htmlFor={`${name}`}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={`${name}`} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<VStack className="mb-4" ref={listRef}>
{items.map((item, index) => (
<ArrayInput
diff --git a/packages/form/src/components/ArrayNumeric.tsx b/packages/form/src/components/ArrayNumeric.tsx
index 5ae1420746..797978d6d6 100644
--- a/packages/form/src/components/ArrayNumeric.tsx
+++ b/packages/form/src/components/ArrayNumeric.tsx
@@ -42,11 +42,13 @@ const ArrayNumeric = forwardRef<HTMLInputElement, FormArrayNumericProps>(
},
ref
) => {
+ const { isOptional: fieldIsOptional } = useField(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || isDisabledProp;
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
const listRef = useRef<HTMLDivElement>(null);
const [items, { push, remove }, error] = useFieldArray<number>(name);
+ const resolvedIsOptional = isRequired ? false : (fieldIsOptional ?? false);
const onAdd = () => {
flushSync(() => {
@@ -61,7 +63,11 @@ const ArrayNumeric = forwardRef<HTMLInputElement, FormArrayNumericProps>(
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
- {label && <FormLabel htmlFor={`${name}`}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={`${name}`} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<VStack className="mb-4" ref={listRef}>
{items.map((item, index) => (
<ArrayNumericInput
diff --git a/packages/form/src/components/Boolean.tsx b/packages/form/src/components/Boolean.tsx
index 1ac7136674..ba2cab3368 100644
--- a/packages/form/src/components/Boolean.tsx
+++ b/packages/form/src/components/Boolean.tsx
@@ -36,7 +36,11 @@ const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(
},
ref
) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const formState = useFormStateContext();
const isDisabled =
formState.isDisabled || formState.isReadOnly || isDisabledProp;
@@ -49,7 +53,11 @@ const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(
return (
<FormControl isInvalid={!!error} className="pt-2">
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<HStack>
<Switch
variant={variant}
diff --git a/packages/form/src/components/Combobox.tsx b/packages/form/src/components/Combobox.tsx
index 4cf33ae1c4..d867e69c00 100644
--- a/packages/form/src/components/Combobox.tsx
+++ b/packages/form/src/components/Combobox.tsx
@@ -34,15 +34,16 @@ const Combobox = ({
name,
label,
isLoading = false,
- isOptional = false,
+ isOptional,
helperText,
...props
}: ComboboxProps) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string | undefined>(name);
const formState = useFormStateContext();
const isReadOnly =
formState.isReadOnly || formState.isDisabled || props.isReadOnly;
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
useEffect(() => {
if (props.value !== null && props.value !== undefined)
@@ -60,7 +61,7 @@ const Combobox = ({
return (
<FormControl isInvalid={!!error}>
{label && (
- <FormLabel htmlFor={name} isOptional={isOptional}>
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
{label}
</FormLabel>
)}
@@ -82,7 +83,7 @@ const Combobox = ({
});
onChange(newValue?.replace(/"/g, '\\"') ?? "");
}}
- isClearable={isOptional && !isReadOnly}
+ isClearable={resolvedIsOptional && !isReadOnly}
isReadOnly={isReadOnly}
isLoading={isLoading}
className="w-full"
diff --git a/packages/form/src/components/CreatableCombobox.tsx b/packages/form/src/components/CreatableCombobox.tsx
index cc6c6b2c30..6d702f34a9 100644
--- a/packages/form/src/components/CreatableCombobox.tsx
+++ b/packages/form/src/components/CreatableCombobox.tsx
@@ -42,17 +42,22 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
label,
helperText,
isConfigured = false,
- isOptional = false,
+ isOptional,
onConfigure,
...props
},
ref
) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [value, setValue] = useControlField<string | undefined>(name);
const formState = useFormStateContext();
const isReadOnly =
formState.isReadOnly || formState.isDisabled || props.isReadOnly;
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
useEffect(() => {
if (props.value !== null && props.value !== undefined)
@@ -84,7 +89,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
htmlFor={name}
isConfigured={isConfigured}
onConfigure={onConfigure}
- isOptional={isOptional}
+ isOptional={resolvedIsOptional}
>
{label}
</FormLabel>
@@ -102,7 +107,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
ref={ref}
{...props}
value={value?.replace(/"/g, '\\"')}
- isClearable={isClearable ?? (isOptional && !isReadOnly)}
+ isClearable={isClearable ?? (resolvedIsOptional && !isReadOnly)}
isReadOnly={isReadOnly}
label={label}
className="w-full"
diff --git a/packages/form/src/components/CreatableMultiSelect.tsx b/packages/form/src/components/CreatableMultiSelect.tsx
index 7a4802c380..02a04cc6cf 100644
--- a/packages/form/src/components/CreatableMultiSelect.tsx
+++ b/packages/form/src/components/CreatableMultiSelect.tsx
@@ -26,84 +26,78 @@ export type CreatableMultiSelectProps = Omit<
const CreatableMultiSelect = forwardRef<
HTMLButtonElement,
CreatableMultiSelectProps
->(
- (
- { name, label, helperText, isOptional = false, options = [], ...props },
- ref
- ) => {
- const { error } = useField(name);
- const [value, setValue] = useControlField<string[] | undefined>(name);
- const formState = useFormStateContext();
- const isReadOnly =
- formState.isReadOnly || formState.isDisabled || props.isReadOnly;
+>(({ name, label, helperText, isOptional, options = [], ...props }, ref) => {
+ const { error, isOptional: fieldIsOptional } = useField(name);
+ const [value, setValue] = useControlField<string[] | undefined>(name);
+ const formState = useFormStateContext();
+ const isReadOnly =
+ formState.isReadOnly || formState.isDisabled || props.isReadOnly;
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
- useEffect(() => {
- if (props.value !== null && props.value !== undefined)
- setValue(props.value);
- }, [props.value, setValue]);
+ useEffect(() => {
+ if (props.value !== null && props.value !== undefined)
+ setValue(props.value);
+ }, [props.value, setValue]);
- const onChange = (value: string[]) => {
- setValue(value);
- props.onChange?.(value);
- };
+ const onChange = (value: string[]) => {
+ setValue(value);
+ props.onChange?.(value);
+ };
- const sortedOptions = useMemo(() => {
- // Split options into selected and unselected
- const selectedOptions = options.filter((opt) =>
- value?.includes(opt.value)
- );
- const unselectedOptions = options.filter(
- (opt) => !value?.includes(opt.value)
- );
+ const sortedOptions = useMemo(() => {
+ // Split options into selected and unselected
+ const selectedOptions = options.filter((opt) => value?.includes(opt.value));
+ const unselectedOptions = options.filter(
+ (opt) => !value?.includes(opt.value)
+ );
- // Sort unselected options alphabetically by label
- const sortedUnselected = [...unselectedOptions].sort((a, b) =>
- a.label.localeCompare(b.label)
- );
+ // Sort unselected options alphabetically by label
+ const sortedUnselected = [...unselectedOptions].sort((a, b) =>
+ a.label.localeCompare(b.label)
+ );
- // Combine selected options first, followed by sorted unselected options
- return [...selectedOptions, ...sortedUnselected];
- }, [options, value]);
+ // Combine selected options first, followed by sorted unselected options
+ return [...selectedOptions, ...sortedUnselected];
+ }, [options, value]);
- return (
- <FormControl isInvalid={!!error}>
- {label && (
- <FormLabel htmlFor={name} isOptional={isOptional}>
- {label}
- </FormLabel>
- )}
- {(value ?? []).filter(Boolean).map((selection, index) => (
- <input
- key={`${name}[${index}]`}
- type="hidden"
- name={`${name}[${index}]`}
- value={selection}
- />
- ))}
- <CreatableMultiSelectBase
- ref={ref}
- {...props}
- options={sortedOptions}
- value={value ?? []}
- onChange={(newValue) => {
- setValue(newValue ?? []);
- onChange(newValue ?? []);
- }}
- isClearable={isOptional && !isReadOnly}
- isReadOnly={isReadOnly}
- label={label}
- className="w-full"
+ return (
+ <FormControl isInvalid={!!error}>
+ {label && (
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
+ {(value ?? []).filter(Boolean).map((selection, index) => (
+ <input
+ key={`${name}[${index}]`}
+ type="hidden"
+ name={`${name}[${index}]`}
+ value={selection}
/>
+ ))}
+ <CreatableMultiSelectBase
+ ref={ref}
+ {...props}
+ options={sortedOptions}
+ value={value ?? []}
+ onChange={(newValue) => {
+ setValue(newValue ?? []);
+ onChange(newValue ?? []);
+ }}
+ isClearable={resolvedIsOptional && !isReadOnly}
+ isReadOnly={isReadOnly}
+ label={label}
+ className="w-full"
+ />
- {error ? (
- <FormErrorMessage>{error}</FormErrorMessage>
- ) : (
- helperText && <FormHelperText>{helperText}</FormHelperText>
- )}
- </FormControl>
- );
- }
-);
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+});
CreatableMultiSelect.displayName = "CreatableMultiSelect";
diff --git a/packages/form/src/components/DatePicker.tsx b/packages/form/src/components/DatePicker.tsx
index 40288975bc..4e70999478 100644
--- a/packages/form/src/components/DatePicker.tsx
+++ b/packages/form/src/components/DatePicker.tsx
@@ -40,7 +40,12 @@ const DatePicker = ({
const isDisabled =
formState.isDisabled || formState.isReadOnly || isDisabledProp;
const { validate } = useFormContext();
- const { error, defaultValue, validate: validateField } = useField(name);
+ const {
+ error,
+ defaultValue,
+ validate: validateField,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [date, setDate] = useState<CalendarDate | undefined>(
value
? parseDate(value)
@@ -84,7 +89,11 @@ const DatePicker = ({
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<input type="hidden" name={name} value={utcValue} />
<DatePickerBase
value={date}
diff --git a/packages/form/src/components/DateTimePicker.tsx b/packages/form/src/components/DateTimePicker.tsx
index df64d1d036..48cd159c09 100644
--- a/packages/form/src/components/DateTimePicker.tsx
+++ b/packages/form/src/components/DateTimePicker.tsx
@@ -43,7 +43,12 @@ const DateTimePicker = ({
const isDisabled =
formState.isDisabled || formState.isReadOnly || isDisabledProp;
const { validate } = useFormContext();
- const { error, defaultValue, validate: validateField } = useField(name);
+ const {
+ error,
+ defaultValue,
+ validate: validateField,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [date, setDate] = useState<CalendarDateTime | undefined>(
defaultValue
? toCalendarDateTime(parseAbsolute(defaultValue, getLocalTimeZone()))
@@ -80,7 +85,11 @@ const DateTimePicker = ({
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<input type="hidden" name={name} value={utcValue} />
<DateTimePickerBase
value={date}
diff --git a/packages/form/src/components/Input.tsx b/packages/form/src/components/Input.tsx
index 2e8397d009..5bb0ae81ae 100644
--- a/packages/form/src/components/Input.tsx
+++ b/packages/form/src/components/Input.tsx
@@ -46,10 +46,16 @@ const Input = forwardRef<HTMLInputElement, FormInputProps>(
},
ref
) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || isDisabledProp;
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
return (
<FormControl
@@ -61,7 +67,7 @@ const Input = forwardRef<HTMLInputElement, FormInputProps>(
{label ? (
<FormLabel
htmlFor={name}
- isOptional={isOptional}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
diff --git a/packages/form/src/components/InputControlled.tsx b/packages/form/src/components/InputControlled.tsx
index 40d48a682a..feb93f281e 100644
--- a/packages/form/src/components/InputControlled.tsx
+++ b/packages/form/src/components/InputControlled.tsx
@@ -23,6 +23,7 @@ type FormInputControlledProps = Omit<InputProps, "value" | "onChange"> & {
name: string;
label?: ReactNode;
isConfigured?: boolean;
+ isOptional?: boolean;
isUppercase?: boolean;
isRequired?: boolean;
helperText?: string;
@@ -40,6 +41,7 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(
name,
label,
isConfigured,
+ isOptional,
isRequired,
helperText,
prefix,
@@ -61,7 +63,11 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(
const isDisabled = formState.isDisabled || isDisabledProp;
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
const { validate } = useFormContext();
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [controlValue, setControlValue] = useControlField<string>(name);
const [inlineMode, setInlineMode] = useState(inline);
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -82,6 +88,8 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(
onChange(isUppercase ? uppercase(e.target.value) : e.target.value);
}
};
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
return inlineMode ? (
<VStack>
@@ -113,6 +121,7 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(
{label && (
<FormLabel
htmlFor={name}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
diff --git a/packages/form/src/components/InputOTP.tsx b/packages/form/src/components/InputOTP.tsx
index 49b7eaf30f..103ff8b2e6 100644
--- a/packages/form/src/components/InputOTP.tsx
+++ b/packages/form/src/components/InputOTP.tsx
@@ -40,10 +40,12 @@ const InputOTP = forwardRef<HTMLInputElement, FormInputOTPProps>(
},
ref
) => {
- const { error } = useField(name);
+ const { error, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string>(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || formState.isReadOnly;
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
useEffect(() => {
if (value?.length === maxLength) {
@@ -61,7 +63,7 @@ const InputOTP = forwardRef<HTMLInputElement, FormInputOTPProps>(
{label ? (
<FormLabel
htmlFor={name}
- isOptional={isOptional}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
diff --git a/packages/form/src/components/MultiSelect.tsx b/packages/form/src/components/MultiSelect.tsx
index 4849aa2dad..44fba97fd1 100644
--- a/packages/form/src/components/MultiSelect.tsx
+++ b/packages/form/src/components/MultiSelect.tsx
@@ -66,7 +66,7 @@ const MultiSelect = ({
maxPreview,
...props
}: MultiSelectProps) => {
- const { error } = useField(name);
+ const { error, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string[]>(name);
const formState = useFormStateContext();
const isReadOnly =
@@ -83,7 +83,11 @@ const MultiSelect = ({
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
{(value ?? []).filter(Boolean).map((selection, index) => (
<input
key={`${name}[${index}]`}
diff --git a/packages/form/src/components/Number.tsx b/packages/form/src/components/Number.tsx
index dd7122a9ea..c73f477767 100644
--- a/packages/form/src/components/Number.tsx
+++ b/packages/form/src/components/Number.tsx
@@ -22,6 +22,7 @@ type FormNumberProps = NumberFieldProps & {
size?: "sm" | "md" | "lg";
label?: string;
isConfigured?: boolean;
+ isOptional?: boolean;
isRequired?: boolean;
helperText?: string;
onConfigure?: () => void;
@@ -34,6 +35,7 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
size = "md",
label,
isConfigured = false,
+ isOptional,
isRequired,
isReadOnly: isReadOnlyProp,
isDisabled: isDisabledProp,
@@ -43,7 +45,11 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
},
ref
) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const formState = useFormStateContext();
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
const isDisabled = formState.isDisabled || isDisabledProp;
@@ -53,6 +59,8 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
minimumFractionDigits: 0,
maximumFractionDigits: 10
} satisfies Intl.NumberFormatOptions);
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
return (
<FormControl
@@ -64,6 +72,7 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
{label && (
<FormLabel
htmlFor={name}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
diff --git a/packages/form/src/components/NumberControlled.tsx b/packages/form/src/components/NumberControlled.tsx
index 356f247447..a83fdb4b9a 100644
--- a/packages/form/src/components/NumberControlled.tsx
+++ b/packages/form/src/components/NumberControlled.tsx
@@ -29,6 +29,7 @@ import { useFormStateContext } from "../internal/formStateContext";
type FormNumberProps = NumberFieldProps & {
name: string;
label?: ReactNode;
+ isOptional?: boolean;
isRequired?: boolean;
helperText?: string;
value: number;
@@ -44,6 +45,7 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
name,
label,
isConfigured,
+ isOptional,
isRequired,
isReadOnly: isReadOnlyProp,
isDisabled: isDisabledProp,
@@ -61,7 +63,11 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
const isDisabled = formState.isDisabled || isDisabledProp;
const { validate } = useFormContext();
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [controlValue, setControlValue] = useControlField<number>(name);
const [inlineMode, setInlineMode] = useState(inline);
const inputRef = useRef<HTMLInputElement>(null);
@@ -80,6 +86,8 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
setControlValue(newValue);
onChange?.(newValue);
};
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
return inlineMode ? (
<VStack>
@@ -118,6 +126,7 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
{label && (
<FormLabel
htmlFor={name}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
diff --git a/packages/form/src/components/Password.tsx b/packages/form/src/components/Password.tsx
index 57fe68074f..32b6418be3 100644
--- a/packages/form/src/components/Password.tsx
+++ b/packages/form/src/components/Password.tsx
@@ -21,15 +21,24 @@ type FormPasswordProps = InputProps & {
const Password = forwardRef<HTMLInputElement, FormPasswordProps>(
({ name, label, isRequired, ...rest }, ref) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || rest.isDisabled;
const isReadOnly = formState.isReadOnly || rest.isReadOnly;
const [passwordVisible, setPasswordVisible] = useState(false);
+ const resolvedIsOptional = isRequired ? false : (fieldIsOptional ?? false);
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<InputGroup>
<Input
{...getInputProps({
diff --git a/packages/form/src/components/PhoneInput.tsx b/packages/form/src/components/PhoneInput.tsx
index f296a70e76..788c8f1d88 100644
--- a/packages/form/src/components/PhoneInput.tsx
+++ b/packages/form/src/components/PhoneInput.tsx
@@ -44,11 +44,12 @@ const PhoneInput: ForwardRefExoticComponent<PhoneInputProps> = forwardRef<
ElementRef<typeof ReactPhoneInput.default>,
PhoneInputProps
>(({ name, label, isRequired, className, ...props }, ref) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string>(name);
const formState = useFormStateContext();
const isDisabled =
formState.isDisabled || formState.isReadOnly || props.disabled;
+ const resolvedIsOptional = isRequired ? false : (fieldIsOptional ?? false);
const onChange = (value: string) => {
setValue(value);
@@ -58,7 +59,11 @@ const PhoneInput: ForwardRefExoticComponent<PhoneInputProps> = forwardRef<
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<PhoneInputComponent
ref={ref}
className={cn("flex", className)}
diff --git a/packages/form/src/components/Radios.tsx b/packages/form/src/components/Radios.tsx
index a11ef70529..3ce96f42b3 100644
--- a/packages/form/src/components/Radios.tsx
+++ b/packages/form/src/components/Radios.tsx
@@ -22,14 +22,18 @@ const Radios = ({
options,
orientation = "vertical"
}: RadiosProps) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || formState.isReadOnly;
const id = useId();
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<RadioGroup
{...getInputProps({
// @ts-ignore
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index fdd8be0ee0..fc98162fd9 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -41,17 +41,18 @@ const Select = ({
label,
helperText,
isConfigured = false,
- isOptional = false,
+ isOptional,
isLoading,
options,
onConfigure,
...props
}: SelectProps) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string | undefined>(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || props.isDisabled;
const isReadOnly = formState.isReadOnly || props.isReadOnly;
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
const onChange = (value: string) => {
if (value) {
@@ -66,7 +67,7 @@ const Select = ({
{label && (
<FormLabel
htmlFor={name}
- isOptional={isOptional}
+ isOptional={resolvedIsOptional}
isConfigured={isConfigured}
onConfigure={onConfigure}
>
@@ -91,7 +92,7 @@ const Select = ({
setValue(newValue ?? "");
onChange(newValue ?? "");
}}
- isClearable={isOptional && !isReadOnly}
+ isClearable={resolvedIsOptional && !isReadOnly}
isDisabled={isDisabled}
isReadOnly={isReadOnly}
isLoading={isLoading}
diff --git a/packages/form/src/components/SelectControlled.tsx b/packages/form/src/components/SelectControlled.tsx
index ca11b445fc..75fe62d22b 100644
--- a/packages/form/src/components/SelectControlled.tsx
+++ b/packages/form/src/components/SelectControlled.tsx
@@ -34,10 +34,11 @@ const SelectControlled = ({
onConfigure,
...props
}: SelectProps) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || props.isDisabled;
const isReadOnly = formState.isReadOnly || props.isReadOnly;
+ const resolvedIsOptional = isOptional ?? fieldIsOptional ?? false;
const [controlValue, setControlValue] = useControlField<string | undefined>(
name
);
@@ -61,7 +62,7 @@ const SelectControlled = ({
<FormLabel
htmlFor={name}
isConfigured={isConfigured}
- isOptional={isOptional}
+ isOptional={resolvedIsOptional}
onConfigure={onConfigure}
>
{label}
diff --git a/packages/form/src/components/Textarea.tsx b/packages/form/src/components/Textarea.tsx
index 63be25ac5b..0708c0f4d9 100644
--- a/packages/form/src/components/Textarea.tsx
+++ b/packages/form/src/components/Textarea.tsx
@@ -19,13 +19,19 @@ type FormTextArea = TextareaProps & {
const TextArea = forwardRef<HTMLTextAreaElement, FormTextArea>(
({ name, label, characterLimit, isRequired, ...rest }, ref) => {
- const { getInputProps, error, defaultValue } = useField(name);
+ const {
+ getInputProps,
+ error,
+ defaultValue,
+ isOptional: fieldIsOptional
+ } = useField(name);
const formState = useFormStateContext();
const disabled = formState.isDisabled || rest.disabled;
const readOnly = formState.isReadOnly || rest.readOnly;
const [characterCount, setCharacterCount] = useState(
defaultValue?.length ?? 0
);
+ const resolvedIsOptional = isRequired ? false : (fieldIsOptional ?? false);
const onChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
if (characterLimit) setCharacterCount(e.target.value.length);
@@ -33,7 +39,11 @@ const TextArea = forwardRef<HTMLTextAreaElement, FormTextArea>(
return (
<FormControl isInvalid={!!error} isRequired={isRequired}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<TextAreaBase
ref={ref}
{...getInputProps({
diff --git a/packages/form/src/components/TextareaControlled.tsx b/packages/form/src/components/TextareaControlled.tsx
index 15876ed857..233874afe9 100644
--- a/packages/form/src/components/TextareaControlled.tsx
+++ b/packages/form/src/components/TextareaControlled.tsx
@@ -15,6 +15,7 @@ type FormTextAreaControlledProps = Omit<TextareaProps, "value" | "onChange"> & {
name: string;
label?: string;
characterLimit?: number;
+ isOptional?: boolean;
isRequired?: boolean;
helperText?: string;
value: string;
@@ -30,6 +31,7 @@ const TextAreaControlled = forwardRef<
name,
label,
characterLimit,
+ isOptional,
isRequired,
helperText,
value,
@@ -39,7 +41,11 @@ const TextAreaControlled = forwardRef<
},
ref
) => {
- const { getInputProps, error } = useField(name);
+ const {
+ getInputProps,
+ error,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [controlValue, setControlValue] = useControlField<string>(name);
const formState = useFormStateContext();
const disabled = formState.isDisabled || rest.disabled;
@@ -58,6 +64,8 @@ const TextAreaControlled = forwardRef<
};
const characterCount = controlValue?.length ?? 0;
+ const resolvedIsOptional =
+ isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
return (
<FormControl
@@ -65,7 +73,11 @@ const TextAreaControlled = forwardRef<
isRequired={isRequired}
className={className}
>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={resolvedIsOptional}>
+ {label}
+ </FormLabel>
+ )}
<TextAreaBase
ref={ref}
{...getInputProps({
diff --git a/packages/form/src/components/TimePicker.tsx b/packages/form/src/components/TimePicker.tsx
index d0faff7f14..029cfb4679 100644
--- a/packages/form/src/components/TimePicker.tsx
+++ b/packages/form/src/components/TimePicker.tsx
@@ -26,7 +26,12 @@ type TimeValue = Time | CalendarDateTime | ZonedDateTime;
const TimePicker = ({ name, label, onChange }: TimePickerProps) => {
const formState = useFormStateContext();
const isDisabled = formState.isDisabled || formState.isReadOnly;
- const { error, defaultValue, validate } = useField(name);
+ const {
+ error,
+ defaultValue,
+ validate,
+ isOptional: fieldIsOptional
+ } = useField(name);
const [time, setDate] = useState<TimeValue | null>(
defaultValue ? parseTime(defaultValue) : null
);
@@ -39,7 +44,11 @@ const TimePicker = ({ name, label, onChange }: TimePickerProps) => {
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<input type="hidden" name={name} value={time?.toString()} />
<TimePickerBase
value={time ?? undefined}
diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsx
index 91c78d26a3..328b30a7d2 100644
--- a/packages/form/src/components/Timezone.tsx
+++ b/packages/form/src/components/Timezone.tsx
@@ -33,7 +33,7 @@ const Timezone = ({
size,
...props
}: TimezoneProps) => {
- const { getInputProps, error } = useField(name);
+ const { getInputProps, error, isOptional: fieldIsOptional } = useField(name);
const formState = useFormStateContext();
const isReadOnly =
formState.isReadOnly || formState.isDisabled || isReadOnlyProp;
@@ -41,7 +41,11 @@ const Timezone = ({
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={fieldIsOptional ?? false}>
+ {label}
+ </FormLabel>
+ )}
<input
{...getInputProps({
id: name
diff --git a/packages/form/src/hooks.ts b/packages/form/src/hooks.ts
index 310e00bdf3..f9cb8c032b 100644
--- a/packages/form/src/hooks.ts
+++ b/packages/form/src/hooks.ts
@@ -16,6 +16,7 @@ import {
useRegisterReceiveFocus,
useSmartValidate
} from "./internal/hooks";
+import { isFieldOptional } from "./internal/isFieldOptional";
import {
useControllableValue,
useUpdateControllableValue
@@ -64,6 +65,11 @@ export type FieldProps = {
* Whether or not the field has been touched.
*/
touched: boolean;
+ /**
+ * Whether this field is optional in the form validator.
+ * `undefined` means the optionality could not be determined.
+ */
+ isOptional?: boolean;
/**
* Helper to set the touched state of the field.
*/
@@ -114,6 +120,11 @@ export const useField = (
return registerReceiveFocus(name, handleReceiveFocus);
}, [handleReceiveFocus, name, registerReceiveFocus]);
+ const optionality = useMemo(
+ () => isFieldOptional(formContext.validatorSchema, name),
+ [formContext.validatorSchema, name]
+ );
+
const field = useMemo<FieldProps>(() => {
const helpers = {
error,
@@ -121,6 +132,7 @@ export const useField = (
validate: () => smartValidate({ alwaysIncludeErrorsFromFields: [name] }),
defaultValue,
touched: !!touched,
+ isOptional: optionality,
setTouched
};
const getInputProps = createGetInputProps({
@@ -138,6 +150,7 @@ export const useField = (
clearError,
defaultValue,
touched,
+ optionality,
setTouched,
name,
hasBeenSubmitted,
diff --git a/packages/form/src/internal/formContext.ts b/packages/form/src/internal/formContext.ts
index 4063bc4f8e..bef937545f 100644
--- a/packages/form/src/internal/formContext.ts
+++ b/packages/form/src/internal/formContext.ts
@@ -1,5 +1,6 @@
import { createContext } from "react";
import type { FetcherWithComponents } from "react-router";
+import type { z } from "zod";
export type InternalFormContextValue = {
formId: string | symbol;
@@ -7,6 +8,7 @@ export type InternalFormContextValue = {
subaction?: string;
defaultValuesProp?: { [fieldName: string]: any };
fetcher?: FetcherWithComponents<unknown>;
+ validatorSchema?: z.ZodTypeAny;
};
export const InternalFormContext =
diff --git a/packages/form/src/internal/isFieldOptional.test.ts b/packages/form/src/internal/isFieldOptional.test.ts
new file mode 100644
index 0000000000..7de78b8f6c
--- /dev/null
+++ b/packages/form/src/internal/isFieldOptional.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod";
+import { isFieldOptional } from "./isFieldOptional";
+
+describe("isFieldOptional", () => {
+ const schema = z.object({
+ requiredName: z.string(),
+ optionalName: z.string().optional(),
+ defaultedName: z.string().default(""),
+ nested: z.object({
+ requiredChild: z.string(),
+ optionalChild: z.string().optional()
+ }),
+ optionalNested: z
+ .object({
+ requiredChild: z.string()
+ })
+ .optional(),
+ items: z.array(
+ z.object({
+ code: z.string().optional()
+ })
+ )
+ });
+
+ it("returns false for required fields", () => {
+ expect(isFieldOptional(schema, "requiredName")).toBe(false);
+ expect(isFieldOptional(schema, "nested.requiredChild")).toBe(false);
+ });
+
+ it("returns true for optional fields", () => {
+ expect(isFieldOptional(schema, "optionalName")).toBe(true);
+ expect(isFieldOptional(schema, "defaultedName")).toBe(true);
+ expect(isFieldOptional(schema, "nested.optionalChild")).toBe(true);
+ expect(isFieldOptional(schema, "optionalNested.requiredChild")).toBe(true);
+ expect(isFieldOptional(schema, "items[0].code")).toBe(true);
+ });
+
+ it("returns undefined when field path is not in schema", () => {
+ expect(isFieldOptional(schema, "missingField")).toBeUndefined();
+ expect(isFieldOptional(schema, "optionalNested.missing")).toBeUndefined();
+ });
+});
diff --git a/packages/form/src/internal/isFieldOptional.ts b/packages/form/src/internal/isFieldOptional.ts
new file mode 100644
index 0000000000..106c2bdf09
--- /dev/null
+++ b/packages/form/src/internal/isFieldOptional.ts
@@ -0,0 +1,109 @@
+import { z } from "zod";
+import { stringToPathArray } from "../utils";
+
+type ZodSchema = z.ZodTypeAny;
+
+function unwrapSchema(schema: ZodSchema): {
+ schema: ZodSchema;
+ isOptional: boolean;
+} {
+ let current: ZodSchema = schema;
+ let isOptional = false;
+
+ while (true) {
+ if (
+ current instanceof z.ZodOptional ||
+ current instanceof z.ZodDefault ||
+ current instanceof z.ZodCatch
+ ) {
+ isOptional = true;
+ current = current._def.innerType;
+ continue;
+ }
+
+ if (current instanceof z.ZodEffects) {
+ current = current._def.schema;
+ continue;
+ }
+
+ if (current instanceof z.ZodNullable) {
+ current = current.unwrap();
+ continue;
+ }
+
+ if (current instanceof z.ZodBranded) {
+ current = current.unwrap();
+ continue;
+ }
+
+ if (current instanceof z.ZodReadonly) {
+ current = current.unwrap();
+ continue;
+ }
+
+ if (current instanceof z.ZodPipeline) {
+ current = current._def.out;
+ continue;
+ }
+
+ return { schema: current, isOptional };
+ }
+}
+
+function getChildSchema(
+ schema: ZodSchema,
+ segment: string | number
+): ZodSchema | null {
+ if (schema instanceof z.ZodObject) {
+ const shape = schema.shape;
+ if (typeof segment !== "string") return null;
+ return shape[segment] ?? null;
+ }
+
+ if (schema instanceof z.ZodArray) {
+ return schema.element;
+ }
+
+ if (schema instanceof z.ZodTuple) {
+ const index =
+ typeof segment === "number"
+ ? segment
+ : Number.isNaN(Number(segment))
+ ? null
+ : Number(segment);
+ if (index === null) return null;
+ return schema.items[index] ?? null;
+ }
+
+ if (schema instanceof z.ZodRecord) {
+ return schema._def.valueType;
+ }
+
+ return null;
+}
+
+export function isFieldOptional(
+ schema: ZodSchema | undefined,
+ fieldName: string
+): boolean | undefined {
+ if (!schema || !fieldName) return undefined;
+
+ const path = stringToPathArray(fieldName);
+ let current: ZodSchema | null = schema;
+ let optionalFromParent = false;
+
+ for (const segment of path) {
+ if (!current) return undefined;
+
+ const unwrapped = unwrapSchema(current);
+ current = unwrapped.schema;
+ optionalFromParent = optionalFromParent || unwrapped.isOptional;
+
+ current = getChildSchema(current, segment);
+ }
+
+ if (!current) return undefined;
+
+ const final = unwrapSchema(current);
+ return optionalFromParent || final.isOptional;
+}