useForm is the React hook for validating form inputs. It returns an object
with several helpers to retrieve error messages and form value, define
validations and more.
useForm returns an object that contains everything you need.
defaultValues: this is the object you provide while initializing the
form so you don't have to define beforehand.
errors: this is an object like {attribute: string[]} which contains all
error messages for invalid attributes. If you need to transform error
messages in any way, use the validations property to derive a new object.
handleChange: the input's onChange handler.
isInvalid(): a function that returns true if the validation fails.
isValid(): a function that returns true if the validation succeeds.
reset(): reset the form's state; i.e. resets validations and errors.
Also restores values to the defaultValues.
validations: an object that contains everything related to the
validation. For more info about the result check Validation.
useForm
is the React hook for validating form inputs. It returns an object with several helpers to retrieve error messages and form value, define validations and more.import React from "react"; import { useForm } from "@fnando/use-form"; type FormParams = { name: string; email: string; password: string; passwordConfirmation: string; }; export const SignupScreen: React.FC = () => { const { errors, values, ...form } = useForm<FormParams>(({ required, confirm, regex }) => ({ name: [required()], email: [required(), regex(/^\S+@\S+$/)], password: [required()], passwordConfirmation: [confirm("password")] })); return ( <form onSubmit={form.handleSubmit}> <p> <label> Your name <br /> <input name="name" onChange={form.handleChange} /> </label> </p> <p> <label> Your email <br /> <input name="email" type="email" onChange={form.handleChange} /> </label> </p> <p> <label> Choose a password <br /> <input name="password" type="password" onChange={form.handleChange} /> </label> </p> <p> <label> Confirm your password <br /> <input name="passwordConfirmation" type="password" onChange={form.handleChange} /> </label> </p> <p> <button>Sign up</button> </p> </form> ); };
useForm
returns an object that contains everything you need.defaultValues
: this is the object you provide while initializing the form so you don't have to define beforehand.errors
: this is an object like{attribute: string[]}
which contains all error messages for invalid attributes. If you need to transform error messages in any way, use thevalidations
property to derive a new object.handleChange
: the input'sonChange
handler.isInvalid()
: a function that returnstrue
if the validation fails.isValid()
: a function that returnstrue
if the validation succeeds.reset()
: reset the form's state; i.e. resetsvalidations
anderrors
. Also restoresvalues
to thedefaultValues
.validations
: an object that contains everything related to the validation. For more info about the result checkValidation
.values
: the current form's state.