Custom validator function for dynamic forms case #125
-
I am working on a simple dynamic form builder - which allows users to pick the form elements they want to have like text, or long text or check box etc, and set the validations like minimum characters, if it is a select, then what are the options etc. So once the user sets the form, it should be made available for the users to fill it, with validation in place. I am stuck at deciding how to get the validation for dynamic forms using remix-validated-forms. I can come up with 2 ways but have no idea on how to get it done
My current implementation without using this library is <TextInput
name={fieldName}
label={question.question}
description={question.description}
className="mt-3 mb-1"
classNames={{
error: "text-xs",
input: "font-semibold",
}}
value={currentValue ? currentValue[fieldName] : ""}
onChange={(event) => {
const value = event.currentTarget.value;
const newFormValue = {
...currentValue,
[fieldName]: value,
};
setCurrentValue(newFormValue);
const result = getValidationForForm()[fieldName](value);
const newFormError = {
...currentError,
[fieldName]: result ? result : null,
};
setCurrentError(newFormError);
}}
error={currentError ? currentError[fieldName] : null}
/> I have two states, one for holding entire form value (currentValue) and one for entire form errors (currentErrors). I validate the field based on the validation function I have defined and set the error. Is there a better way? Please let me know if there is a way or if needed I can get more information on what the problem is. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I would lean towards dynamically building a zod schema based on the chosen parameters. If you really want to make a custom validator, you can create an adapter for it.
To validate on every change, you can customize the As for storing form values, this library doesn't store the values at all because we're just submitting the raw form data in the end. You can track field values with
This part makes me thing I think I might be misunderstanding the premise. Are the dynamic forms going to be consumed by developers or by users of the app? I wouldn't expect you'd be able to determine anything validation related until runtime if the forms are being generated by users. Hopefully that helps! Let me know if you have any more questions. |
Beta Was this translation helpful? Give feedback.
I would lean towards dynamically building a zod schema based on the chosen parameters. If you really want to make a custom validator, you can create an adapter for it.
To validate on every change, you can customize the
validationBehavior
ofuseField
.As for storing form values, this library doesn't store the values at all because we're just submitting the raw form data in the end. You can track field values with
useControlField
though.