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';23export 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 });1011 await schema.validate(data, {12 abortEarly: false,13 });1415 // Validation passed16 console.log(data);17 } catch (err) {18 if (err instanceof Yup.ValidationError) {19 // Validation failed20 console.log(err);21 }22 }23 }2425 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';34export default function SignIn() {5 const formRef = useRef(null);67 async function handleSubmit(data) {8 try {9 // Remove all previous errors10 formRef.current.setErrors({});1112 const schema = Yup.object().shape({13 email: Yup.string()14 .email()15 .required(),16 password: Yup.string()17 .min(6)18 .required(),19 });2021 await schema.validate(data, {22 abortEarly: false,23 });2425 // Validation passed26 console.log(data);27 } catch (err) {28 const validationErrors = {};2930 if (err instanceof Yup.ValidationError) {31 err.inner.forEach(error => {32 validationErrors[error.path] = error.message;33 });3435 formRef.current.setErrors(validationErrors);36 }37 }38 }3940 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);45 useEffect(...); // Same useEffect from basic form example67 return (8 <>9 <input10 ref={inputRef}11 defaultValue={defaultValue}12 className={error ? 'has-error' : ''}13 {...rest}14 />1516 { error && <span className="error">{error}</span> }17 </>18 );19}