I am using Mantine form for my UI and client side validation: https://mantine.dev/form/validation/
Here is an example of using it:
import { useForm } from '@mantine/form';
import { NumberInput, TextInput, Button } from '@mantine/core';
function Demo() {
const form = useForm({
mode: 'uncontrolled',
initialValues: { name: '', email: '', age: 0 },
// functions will be used to validate values at corresponding key
validate: {
name: (value) => (value.length < 2 ? 'Name must have at least 2 letters' : null),
email: (value) => (/^S+@S+$/.test(value) ? null : 'Invalid email'),
age: (value) => (value < 18 ? 'You must be at least 18 to register' : null),
},
});
return (
<form onSubmit={form.onSubmit(console.log)}>
<TextInput
label="Name"
placeholder="Name"
key={form.key('name')}
{...form.getInputProps('name')}
/>
<TextInput
mt="sm"
label="Email"
placeholder="Email"
key={form.key('email')}
{...form.getInputProps('email')}
/>
<NumberInput
mt="sm"
label="Age"
placeholder="Age"
min={0}
max={99}
key={form.key('age')}
{...form.getInputProps('age')}
/>
<Button type="submit" mt="sm">
Submit
</Button>
</form>
);
}
I am trying to have both client and server side validation with server actions. A different library that is not UI based, conform, has an example of this:
https://conform.guide/integration/nextjs
Here is a snippet:
export function LoginForm() {
const [lastResult, action] = useFormState(login, undefined);
const [form, fields] = useForm({
// Sync the result of last submission
lastResult,
// Reuse the validation logic on the client
onValidate({ formData }) {
return parseWithZod(formData, { schema: loginSchema });
},
// Validate the form on blur event triggered
shouldValidate: 'onBlur',
shouldRevalidate: 'onInput',
});
return (
<form id={form.id} onSubmit={form.onSubmit} action={action} noValidate>
I have been attempting to have the same resulting code of onSubmit
and action
with Mantine form, but all attempts fail me. I have attempted the following as an example:
<form
ref={formRef}
onSubmit={form.onSubmit((values, event) => {
event?.stopPropagation();
formRef.current?.submit();
})}
action={formAction}
>
For some reason, the server action never gets triggered. I have a feeling that the conform library has some magic involved that allows this to work. I would just like to get the same working setup with Mantine form. Any help is appreciated.