React form Validation

Description

When works with real application validations forms is very common because this is the way you can verify if the input's value is correct or not. There are several validations solutions available, but when we use useForm the default solution is Yup.With yup the process of validations is very simple and powerful.

The useform returns an error object, that has all errors, and this object is updated every time the input is changed or when the form is submitted if you are using an uncontrolled form.

It's important you remember that to show error the correct way you need knows if an input with error is touched or not. You can discover this information with an object called touched, this object has all properties the initial values object but instead of values, the object has a boolean value, this boolean value shows you if a specific input was touched.

Usage

The validation is runes every time the state is changed. By default, the useForm uses the option uncontrolled inputs, it means that values are accessible when onSubmit event is dispatched.

import {useForm} from 'useforms'
import * as yup from 'yup'
const initialValues = {
name:"Jesse",
email:"jesse@jesse.com",
pets:["felix"],
accept:false
}
const validation = yup.object().shape({
name: yup.string().required("This field is required"),
email: yup.string().email("This field must be a valid e-mail").required("This field is required"),
pets: yup.array(yup.string().required("This field is required")),
accept:yup.bool().oneOf([true], 'Field must be checked')
})
function ControlledForm(){
const [{values, reset},{input}] = useForm({onChange:true, initialValues, validation})
return (
<>
<input {...input("name", "text")}/>
<span>{touched.name && errors.name}</span>
<input {...input("email" ,"email")}/>
<span>{touched.email && errors.email}</span>
<input {...input("pets.0" ,"text")}/>
<span>{touched.pets?.[0] && errors.pets?.[0]}</span>
<input {...input("accept", "checkbox")}/>
<span>{touched.accept && errors.accept}</span>
</>
)
}

Demo

Form
Values
{
  "name": "jesse",
  "email": "jesse@jesse.com",
  "pets": [
    "felix"
  ],
  "accept": false
}
Errors
{}

useValidation

usevalidation is a custom hook, every time the input value is changed that hook is called and udate object error. This hook makes the same work that useForm makes, you can use this hook if you want to get more control about form validation. This hook receives the values and a yup validation schema, and return the object errors.

Usage

const validation = yup.object().shape({...})
const { errors, isValid } = useValidation(values, validation)