Unform

Validation

Validation

Unform does not include validation in its core, so you can choose the best library that fits your application needs.

In the example below, we showcase form validation with Yup.

Validation with Yup

1import * as Yup from 'yup';
2
3export default function SignIn() {
4 async function handleSubmit(data) {
5 try {
6 const schema = Yup.object().shape({
7 email: Yup.string().email().required(),
8 password: Yup.string().min(6).required(),
9 });
10
11 await schema.validate(data, {
12 abortEarly: false,
13 });
14
15 // Validation passed
16 console.log(data);
17 } catch (err) {
18 if (err instanceof Yup.ValidationError) {
19 // Validation failed
20 console.log(err);
21 }
22 }
23 }
24
25 return (...);
26}

Displaying errors

If you need to set and get errors inside inputs, you can use the setErrors method.

SignIn.jsx
1import React, { useRef } from 'react';
2import * as Yup from 'yup';
3
4export default function SignIn() {
5 const formRef = useRef(null);
6
7 async function handleSubmit(data) {
8 try {
9 // Remove all previous errors
10 formRef.current.setErrors({});
11
12 const schema = Yup.object().shape({
13 email: Yup.string()
14 .email()
15 .required(),
16 password: Yup.string()
17 .min(6)
18 .required(),
19 });
20
21 await schema.validate(data, {
22 abortEarly: false,
23 });
24
25 // Validation passed
26 console.log(data);
27 } catch (err) {
28 const validationErrors = {};
29
30 if (err instanceof Yup.ValidationError) {
31 err.inner.forEach(error => {
32 validationErrors[error.path] = error.message;
33 });
34
35 formRef.current.setErrors(validationErrors);
36 }
37 }
38 }
39
40 return (
41 <Form ref={formRef} onSubmit={handleSubmit}>
42 ...
43 </Form>
44 );
45}

Inside the input component, you need to get error from useField and display it. You can also use the error message to add new classes or style the input.

components/Input.js
1export default function Input({ name, ...rest }) {
2 const inputRef = useRef(null);
3 const { fieldName, defaultValue, registerField, error } = useField(name);
4
5 useEffect(...); // Same useEffect from basic form example
6
7 return (
8 <>
9 <input
10 ref={inputRef}
11 defaultValue={defaultValue}
12 className={error ? 'has-error' : ''}
13 {...rest}
14 />
15
16 { error && <span className="error">{error}</span> }
17 </>
18 );
19}
Edit this page on GitHub