React Hook Form Validation - quotehound/v2QHForms GitHub Wiki
React hooks form validation allows us to streamline our validation process for each form. This then allows us to set rules for each item and validate as we go. https://react-hook-form.com/
We Will use React Hook Form Validation with React Toastify notification system to show errors.
npm install react-hook-form
import React from "react";
import { useForm } from "react-hook-form"; // This is where we import librrary
export default function App() {
const { register, handleSubmit, watch, errors } = useForm(); // set const for React hook
const onSubmit = data => console.log(data); // Logs Data for validation
console.log(watch("example")); // watch input value by passing the name of it
return (
/* "handleSubmit" will validate your inputs before invoking "onSubmit" */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input name="example" defaultValue="test" ref={register} />
{/* include validation with required or other standard HTML validation rules */}
<input name="exampleRequired" ref={register({ required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
One of the key concepts in React Hook Form is to register your uncontrolled component into the hook. This will make its value available for both the form validation and submission.
Note: Each field is required to have a unique name as a key for the registration process.
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={register} />
<select name="gender" ref={register}>
<option value="female">female</option>
<option value="male">male</option>
<option value="other">other</option>
</select>
<input type="submit" />
</form>
);
}
React Hook Form makes form validation easy by aligning with the existing HTML standard for form validation.
List of validation rules supported:
- required - bool
- min - int
- max - int
- minLength - int
- maxLength - int
- pattern -
- validate -
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={register({ required: true, maxLength: 20 })} />
<input name="lastName" ref={register({ pattern: /^[A-Za-z]+$/i })} />
<input name="age" type="number" ref={register({ min: 18, max: 99 })} />
<input type="submit" />
</form>
);
}
React Hook Form provides an errors object to show you the errors in the form.
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, errors, handleSubmit } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && "First name is required"}
<Input name="lastName" ref={register({ required: true })} />
{errors.lastName && "Last name is required"}
<input type="submit" />
</form>
);
}
It's pretty common to collect user information through different pages and sections. We need to use Little State Machine in order to use routes as state management library to store user input through different pages or sections
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { StateMachineProvider, createStore } from "little-state-machine";
import Step1 from "./Step1";
import Step2 from "./Step2";
import Result from "./Result";
createStore({
data: {
firstName: '',
lastName: '',
}
});
export default function App() {
return (
<StateMachineProvider>
<Router>
<Route exact path="/" component={Step1} />
<Route path="/step2" component={Step2} />
<Route path="/result" component={Result} />
</Router>
</StateMachineProvider>
);
}
import React from "react";
import { useForm } from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";
const Step1 = props => {
const { register, handleSubmit } = useForm();
const { actions } = useStateMachine({ updateAction });
const onSubmit = data => {
actions.updateAction(data);
props.history.push("./step2");
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input {...register("lastName")} />
<input type="submit" />
</form>
);
};
export default withRouter(Step1);
import React from "react";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";
const Result = props => {
const { state } = useStateMachine(updateAction);
return <pre>{JSON.stringify(state, null, 2)}</pre>;
};