Unform

Validation

Unform does not includes validation by default, so you can choose the best library that fits for you.

Let's see an example using Yup to validate form fields.

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

Unform provides an easy way to set and get errors inside inputs:

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().email().required(),
14 password: Yup.string().min(6).required(),
15 });
16
17 await schema.validate(data, {
18 abortEarly: false,
19 });
20
21 // Validation passed
22 console.log(data);
23 } catch (err) {
24 const validationErrors = {};
25
26 if (err instanceof Yup.ValidationError) {
27 err.inner.forEach(error => {
28 validationErrors[error.path] = error.message;
29 });
30
31 formRef.current.setErrors(validationErrors);
32 }
33 }
34 }
35
36 return (
37 <Form ref={formRef} onSubmit={handleSubmit}>
38 ...
39 </Form>
40 )
41}

And inside the input component you need to get error from useField and display it.

You can also use the error message to add new class or styles to 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