Pattern for required values that start out empty #631
Replies: 3 comments 1 reply
-
|
I think you have to decide where you schema boundary is, and maybe some of this depends on your use-case. I would personally approach this as two schemas if you have two different cases: one for the schema that describes the possible range of values of your form state, and one for the schema that describes your application model's runtime constraints. The first case is often not that useful to have a schema for. Something like: const schema = z.object({
author: z.object({
value: z.string(),
label: z.string(),
}),
});
type Schema = z.output<typeof schema>;
interface FormData {
author: Schema["author"] | null;
} |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for your reply. I agree that the schema for the form state isn't necessarily useful here. My main concern is DRY, since it's a fairly common pattern to start forms out as empty. For every valid schema it would be required to go through and pick out where the optional values are needed. Especially in the case where empty strings are "valid" defaults (typically the case), where-as empty dates, or empty numbers are not, even if they are ultimately required: Obviously the purpose of this library goes beyond solely form validation, but it seems like a common enough pattern to address in some fashion. |
Beta Was this translation helpful? Give feedback.
-
|
I'm guessing you're leaning towards null to keep a MUI input element or simliar as controlled, otherwise it would seem the new .partialBy() method may fit the bill here (not sure if it's released yet, though??). You could always null coalesce on the value prop of the input element, ie. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a common pattern to handling a value that is required, but starts out as an empty value? For example, say I'm creating a task and it should have an owner. My schema would look like so:
However, there's no user that is selected by default and the field is clearable, so as part of the API it would allow setting null. Obviously I could add
nullable, butnullshould end up raising an error indicating that a value is required. What is the best way to allow null as a value, but validate that the value isn't null? Is usingrefinethe expected case here?Beta Was this translation helpful? Give feedback.
All reactions