Form submission

Handle submit, transform values, async submission and server errors

onSubmit handler

form.onSubmit creates the onSubmit handler for the form element. It calls event.preventDefault(), validates the form and then calls one of two callbacks:

  • handleSubmit – called with form values when validation passes
  • handleValidationFailure – optional, called with validation errors when validation fails
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm();

  return (
    <form
      onSubmit={form.onSubmit(
        (values, event) => {
          console.log(values); // form.getValues() at the moment of submit
        },
        (validationErrors, values, event) => {
          console.log(validationErrors); // form.errors at the moment of submit
        }
      )}
    />
  );
}

Use handleValidationFailure to perform an action when the user tries to submit a form with invalid values, for example, to show a notification:

import { useForm } from '@mantine/form';
import { TextInput, Button } from '@mantine/core';
import { notifications } from '@mantine/notifications';

function Demo() {
  const form = useForm({
    initialValues: { name: '', email: '' },
    validate: {
      name: (value) => (value.length < 2 ? 'Name must have at least 2 letters' : null),
      email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'),
    },
  });

  const handleError = (errors: typeof form.errors) => {
    if (errors.name) {
      notifications.show({ message: 'Please fill name field', color: 'red' });
    } else if (errors.email) {
      notifications.show({ message: 'Please provide a valid email', color: 'red' });
    }
  };

  return (
    <form onSubmit={form.onSubmit(console.log, handleError)}>
      <TextInput
        label="Name"
        placeholder="Name"
        {...form.getInputProps('name')}
      />
      <TextInput
        mt="sm"
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />
      <Button type="submit" mt="sm">
        Submit
      </Button>
    </form>
  );
}

Focus the first invalid field

form.focusInput('path') focuses an input or the first enabled control inside a group. Use it in handleValidationFailure to focus the first invalid field. form.getInputNode('path') still returns the element with data-path for DOM access. In a custom control, put data-form-focus on its preferred focusable child if it is not the first input:

Preferred contact
import { Button, Group, Radio, TextInput } from '@mantine/core';
import { isEmail, isNotEmpty, useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    name: 'register-form',
    initialValues: {
      name: '',
      email: '',
      contact: '',
    },

    validate: {
      name: isNotEmpty('Name is required'),
      email: isEmail('Invalid email'),
      contact: isNotEmpty('Choose how to contact you'),
    },
  });

  return (
    <form
      onSubmit={form.onSubmit(
        (values) => console.log(values),
        (errors) => {
          const firstErrorPath = Object.keys(errors)[0];
          form.focusInput(firstErrorPath);
        }
      )}
    >
      <TextInput
        withAsterisk
        label="Your name"
        placeholder="Your name"
        {...form.getInputProps('name')}
      />

      <TextInput
        withAsterisk
        label="Your email"
        placeholder="your@email.com"
        mt="md"
        {...form.getInputProps('email')}
      />

      <Radio.Group label="Preferred contact" withAsterisk mt="md" {...form.getInputProps('contact')}>
        <Radio label="Email" value="email" />
        <Radio label="Phone" value="phone" />
      </Radio.Group>

      <Group justify="flex-end" mt="md">
        <Button type="submit">Submit</Button>
      </Group>
    </form>
  );
}

Submitting state

form.submitting is true while the promise returned from handleSubmit is pending. It is set back to false when the promise resolves or rejects. Use it to disable inputs and show a loading state on the submit button:

import { useState } from 'react';
import { Button, Group, Stack, Text, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

const asyncSubmit = (values: any) =>
  new Promise((resolve) => setTimeout(() => resolve(values), 3000));

function Demo() {
  const form = useForm({
    initialValues: { name: 'John' },
  });

  const [completed, setCompleted] = useState(false);

  const handleSubmit = async (values: typeof form.values) => {
    await asyncSubmit(values);
    setCompleted(true);
  };

  if (completed) {
    return (
      <Stack>
        <Text>Form submitted!</Text>
        <Button onClick={() => setCompleted(false)}>Reset to initial state</Button>
      </Stack>
    );
  }

  return (
    <form onSubmit={form.onSubmit(handleSubmit)}>
      <TextInput
        withAsterisk
        label="Name"
        placeholder="Your name"
        disabled={form.submitting}
        {...form.getInputProps('name')}
      />

      <Group justify="flex-end" mt="md">
        <Button type="submit" loading={form.submitting}>
          Submit
        </Button>
      </Group>
    </form>
  );
}

You can also set form.submitting manually with form.setSubmitting:

import { useForm } from '@mantine/form';

const form = useForm();
form.submitting; // -> false

form.setSubmitting(true);
form.submitting; // -> true

form.setSubmitting(false);
form.submitting; // -> false

Server errors

To display errors returned from the backend, call form.setErrors or form.setFieldError in handleSubmit. Errors are cleared when the user changes the field value. See Form errors for all error handlers:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: { email: '' },
  });

  const handleSubmit = async (values: typeof form.values) => {
    const response = await fetch('/api/register', {
      method: 'POST',
      body: JSON.stringify(values),
    });

    if (response.status === 422) {
      // Response body: { email: 'Email is already taken' }
      form.setErrors(await response.json());
    }
  };

  return <form onSubmit={form.onSubmit(handleSubmit)} />;
}

transformValues

Use transformValues to transform values before they get submitted in the onSubmit handler. For example, it can be used to merge several fields into one or to convert types:

import { useState } from 'react';
import { useForm } from '@mantine/form';
import { TextInput, Button, Code } from '@mantine/core';

function Demo() {
  const [submittedValues, setSubmittedValues] = useState('');

  const form = useForm({
    initialValues: {
      firstName: 'Jane',
      lastName: 'Doe',
      age: '33',
    },

    transformValues: (values) => ({
      fullName: `${values.firstName} ${values.lastName}`,
      age: Number(values.age) || 0,
    }),
  });

  return (
    <>
      <form
        onSubmit={form.onSubmit((values) => setSubmittedValues(JSON.stringify(values, null, 2)))}
      >
        <TextInput
          label="First name"
          placeholder="First name"
          {...form.getInputProps('firstName')}
        />
        <TextInput
          label="Last name"
          placeholder="Last name"
          mt="md"
          {...form.getInputProps('lastName')}
        />
        <TextInput
          type="number"
          label="Age"
          placeholder="Age"
          mt="md"
          {...form.getInputProps('age')}
        />
        <Button type="submit" mt="md">
          Submit
        </Button>
      </form>

      {submittedValues && (
        <Code block mt="md">
          {submittedValues}
        </Code>
      )}
    </>
  );
}

Get transformed values

form.getTransformedValues returns transformed values outside of form.onSubmit. Pass values to transform as an argument, by default it transforms form.getValues():

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      firstName: 'John',
      lastName: 'Doe',
    },

    transformValues: (values) => ({
      fullName: `${values.firstName} ${values.lastName}`,
    }),
  });

  form.getTransformedValues(); // -> { fullName: 'John Doe' }
  form.getTransformedValues({
    firstName: 'Jane',
    lastName: 'Loe',
  }); // { fullName: 'Jane Loe' }
}

To type a submit handler declared outside of form.onSubmit, use the TransformedValues type.

onSubmitPreventDefault option

onSubmitPreventDefault option controls when form.onSubmit calls event.preventDefault():

  • always (default) - always call event.preventDefault()
  • never - never call event.preventDefault()
  • validation-failed - call event.preventDefault() only if validation failed
import { useForm } from '@mantine/form';

const form = useForm({
  onSubmitPreventDefault: 'never',
});

onReset handler

form.onReset is the onReset handler for the form element, it calls form.reset. Use it with a type="reset" button to reset the form:

import { Button } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm();

  return (
    <form onSubmit={form.onSubmit(console.log)} onReset={form.onReset}>
      <Button type="reset">Reset</Button>
      <Button type="submit">Submit</Button>
    </form>
  );
}