Track isSubmitted and isValid state client-side #321
-
If a user submits a form but it fails validation, I like to display some red text near the submit button: "Uh oh, your form has errors!" React-hook-form passes a form state that includes I've figured out a way to get what I need by patching a few methods: export default function SignUp() {
const [isSubmitted, setSubmitted] = useState(false);
const [isValid, setValid] = useState(false);
const lastSubmission = useActionData<typeof action>();
const [form, fields] = useForm({
lastSubmission,
shouldValidate: "onBlur",
onValidate({ formData }) {
setValid(false);
const parsed = parse(formData, { schema });
if (Object.keys(parsed.error).length === 0) setValid(true);
return parsed;
},
});
return (
<Form
method="post"
{...form.props}
onSubmit={(e) => {
setSubmitted(true);
form.props.onSubmit(e);
}}
>
{/* form */}
{isSubmitted && !isValid && <p>Uh oh, your form has errors!</p>}
</Form>
)
} This does a couple of things: when the form is submitted, I'm using a useState hook to set an isSubmitted variable to true. This happens regardless of whether the form is valid or not. Then, whenever onValidate runs, I'm using a separate useState hook to set isValid to true or false, depending on whether the form is valid. This works, but it's not very portable. I'll have to set the custom onSubmit and onValidate wherever I use this form library. Am I missing something built in? Is there a more straightforward way to get the formState I'm looking for? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Did you try to display the form errors ? {form.errors.length > 0 &&
<p>{JSON.stringify(form.errors)}</p> // or <p>{form.error}</p> for the first encountered error
} |
Beta Was this translation helpful? Give feedback.
-
Well, it looks like some additional form state may be coming in a future release. |
Beta Was this translation helpful? Give feedback.
-
There is no built-in state for these at the moment but we will have them supported very soon as you found :) What you have above looks valid to me. But be aware that const [form, fields] = useForm({
lastSubmission,
shouldValidate: "onBlur",
onValidate({ formData }) {
const parsed = parse(formData, { schema });
setValid(Object.keys(parsed.error).length === 0);
if (parsed.intent === 'submit') setSubmitted(true);
return parsed;
},
}); |
Beta Was this translation helpful? Give feedback.
There is no built-in state for these at the moment but we will have them supported very soon as you found :)
What you have above looks valid to me. But be aware that
onSubmit
is called only if there is no error, so if your consider the formsubmitted
regardless there is any error, you can do this instead: