Unform

Get/set field error

Get/set field error

Unform provides an easy way to set or access input errors by using the form ref.

1export default function MyForm() {
2 const formRef = useRef(null);
3
4 function functionThatGetsErrors() {
5 // Get all errors
6 const allErrors = formRef.current.getErrors();
7
8 // Get single field error
9 const name = formRef.current.getFieldError('name');
10 const street = formRef.current.getFieldError('address.street');
11
12 console.log(allErrors, name, street);
13 }
14
15 function functionThatSetsErrors() {
16 // Set all errors
17 formRef.current.setErrors({
18 name: 'Name is required',
19 address: {
20 street: 'Street not found',
21 },
22 });
23
24 // Set single field error
25 formRef.current.setFieldError('name', 'Name is required');
26 formRef.current.setFieldError('address.street', 'Street not found');
27 }
28
29 return (
30 <Form ref={formRef}>
31 <Input name="name" />
32
33 <Scope path="address">
34 <Input name="street" />
35 <Input name="number" />
36 </Scope>
37 </Form>
38 );
39}
Edit this page on GitHub